CS 200 Objects and ArrayList Jim Williams, PhD
This Week Consulting Hours BP1: Milestone 2 due this week TA may just have a few minutes before moving on. BP1: Milestone 2 due this week Team Lab: Multi-Dimensional Arrays Bring paper and pencil to draw diagrams. Style and Commenting Standards Lecture: Objects and ArrayList comparison with arrays
Object Concept A way to group together related variables and methods.
Object class java.lang.Object Every class is a descendent of Object, either directly or indirectly. Primitives are not descendents of Object. has methods such as toString() that are inherited by every class.
class vs instance/object Object,String,Random,Scanner,Integer instance/object instantiated with: new String("hello") new Integer(3) new Random() new Scanner( System.in)
Constructor A special method only called when initially creating an instance/object. Called to initialize fields of instance/object, after memory is allocated.
Recall Wrapper Classes Primitive Data Type Wrapper class int Integer double Double char Character etc. Boxing: create an instance of wrapper class for primitive value. Unboxing: get primitive value from instance of wrapper class. Java Language Specification https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html
Printing out, toString method Integer [] list = {1,2,3}; System.out.println( list[1] ); System.out.println( list ); //java.util.Arrays.toString( list)
Motivation for ArrayList Add 7 to array int [] list = new int[]{1,4,5}; list[3] = 7; //?error Write a method public static int [] addElement(int [] list, int elem) { //? } public static int [] addElementAtEnd(int [] list, int elem) { int newLength = list.length + 1; int [] newList = new int[newLength]; for ( int i = 0; i < list.length; i++) { newList[i] = list[i]; } newList[newList.length -1] = elem; return newList;
Arrays vs ArrayList Arrays fixed length, constant access time contents any type (primitive or reference) ArrayList contents only Reference types automatically grows as elements are added by allocating a new array and copying.
Creating an ArrayList Declaration The variable now exists and is for holding a reference to an ArrayList for reference type. ArrayList< ReferenceType > varName Instantiation allocates memory and calls a constructor new ArrayList< ReferenceType >() ArrayList<String> list = new ArrayList<String>();
Question String int Random Scanner Object Which of the following Cannot be used as the datatype of an element in an ArrayList?
Java Source Code Usually within Java Development Kit (JDK). On Windows typically found under: C:\Program Files\Java Look for src.zip Since java.util.ArrayList look in java\util\ for ArrayList.java API created from source JavaDoc comments
Question What path in source code folder would you look to find Scanner.java?
ArrayList Fields (variables in each instance) int size Object [] elementData Constructors ArrayList() //default capacity of 10 ArrayList( int initialCapacity)
ArrayList Diagram ArrayList<Integer> list; list = new ArrayList<Integer>(); list.add( 2); list.add(0,3); System.out.println( list);
Today Hours Spent in Last Week
Draw a Diagram ArrayList<Integer> list; list = new ArrayList<Integer>(20); list.add(0,3); list.add(5); list.add(0,4); list.remove( 1); System.out.println( list);
How many elements? ArrayList<Integer> list4; list4 = new ArrayList<Integer>(100); for ( int i = 0; i < 1000; i++) { list4.add( i); } System.out.println( list4.size()); 1000 100 error (after 100 added)
Capacity vs Size Capacity Size array .length attribute programmer keeps separate count of elements inserted in array ArrayList automatically changes as needed .size() method
How to retrieve the number of elements added to an Array vs ArrayList? A arr.length B list.size() B list.length() A arr.size Other static int numElements(int [] arr) { return A; } static int numElements(ArrayList list) { return B; correct: A (try it)
Question With the goal of minimizing the running time of your program, how would you declare and instantiate an ArrayList, called temps, to store a sequence of at least 100,000 temperature measurements?
What size and elements? 5 [A,B,C,D,E] ArrayList<String> list; list = new ArrayList<String>(); list.add("A"); list.add(0,"B"); list.add("C"); list.set(2,"D"); list.add("E"); System.out.println( list.size()); System.out.println( list); 5 [A,B,C,D,E] 4 [B, A, D, E] 3 [B,D,E] error or other
Enhanced For Loop ArrayList<String> names = new ArrayList<>(); names.add("spot"); names.add("fido"); for ( String name : names) { System.out.println( name); }
Draw a Diagram ArrayList<int[]> nums = new ArrayList<>(); nums.add(new int[] {1, 2}); nums.add(new int[] {4, 5, 6}); nums.add(new int[] {7, 8, 9}); nums.add(nums.get(1)); nums.remove(1); nums.get(1)[0] = 3; import java.util.ArrayList; public class Week9 { public static void main(String[] args) { ArrayList<int[]> nums = new ArrayList<>(); nums.add(new int[] {1, 2}); nums.add(new int[] {4, 5, 6}); nums.add(new int[] {7, 8, 9}); nums.add(nums.get(1)); nums.remove(1); nums.get(1)[0] = 3; for (int[] arr : nums) { System.out.println(java.util.Arrays.toString(arr)); }
Draw a Diagram [[],[],[]] ArrayList<ArrayList<String>> list = new ArrayList<>(); list.add( new ArrayList<String>()); list.add(1, new ArrayList<String>()); list.get(1).add("D"); list.set(0, list.get(1)); list.get(2).clear(); System.out.println( list); [[],[],[]] [[], [D], []] [[D],[D],[]] error or other try it.
Common Algorithms Searching Sorting Palindrome?
Linear Search //Returns the index of where the element x was //found or -1 if not found. public static int linearSearch( ArrayList<Integer> list, int x) { } /** * Returns the index of where the element x was found * or -1 if not found. * @param arr * @param x * @return */ public static int linearSearch( int arr[], int x) { for ( int i = 0; i < arr.length; i++) { if ( arr[i] == x) { return i; } return -1;
Binary Search // Return index of where x is in list if found, // otherwise returns -1; public static int binarySearch(ArrayList<Integer> list, int x) { } /* * Return index of where x is in array if found, otherwise * returns -1; */ public static int binarySearch(int arr[], int x) { int left = 0, right = arr.length - 1; while (left <= right) { //determine mid point int mid = left + (right-left)/2; //check mid point if (arr[mid] == x) return mid; //if x is greater than mid point then change left if (arr[mid] < x) left = mid + 1; //if x is less than mid point then change right else right = mid - 1; } //not found, return -1 return -1;
Sorting Demo 9, 6, 4, 5, 8, 2 import java.util.Arrays; public class BubbleSort { public static void swapInts(int a, int b) { int temp = a; a = b; b = temp; } public static void main(String[] args) { int x = 1; int y = 2; System.out.println("x = " + x + ", y = " + y); swapInts(x, y); int[] list = new int[]{10, 5, 3, 7, 9}; printArray(list); swapInts(list[0], list[4]); swapElements(list, 0, 4); bubbleSort(list); addElementAtEnd(list, 12); list = addElementAtEnd(list, 4); public static void printArray( int [] arr) { System.out.println( Arrays.toString( arr)); public static void swapElements(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; public static void bubbleSort(int[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length -1; j++) { if (arr[j] > arr[j+1]) { swapElements(arr, j, j+1); public static int[] addElementAtEnd( int[] arr, int elem) { int newLength = arr.length + 1; int[] newArray = new int[newLength]; newArray[i] = arr[i]; newArray[newArray.length - 1] = elem; return newArray;