Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 200 Objects and ArrayList

Similar presentations


Presentation on theme: "CS 200 Objects and ArrayList"— Presentation transcript:

1 CS 200 Objects and ArrayList
Jim Williams, PhD

2 This Week Due Thursday Office Hours Team Lab: Multi-Dimensional Arrays
Chap 8 zyLabs, 3 parts Code Refactor 1: Wumpus Caves Office Hours TA may just have a few minutes before rotating. Team Lab: Multi-Dimensional Arrays Bring paper and pencil to draw diagrams. Lecture: Objects and ArrayList comparison with arrays

3 Programming Paradigms
Procedural paradigm and using objects Write static/class methods and pass data structures Use predefined classes: Scanner, String, Integer Focus of CS 200 Object-Oriented paradigm Grouping of related data and methods Interaction of objects Create your own instantiable classes Key part of CS 300

4 Object Concept Group related data and methods Scanner class
input and methods to access String class series of characters and related methods Integer class int value and methods to convert to/from that value

5 Object class java.lang.Object Special class in Java
Every class is a descendent of Object, either directly or indirectly. e.g., Scanner, String, Integer Primitives are not descendents of Object Has methods such as equals() and toString() that are inherited by every class

6 See extends relationship in API

7 Class vs Instance/Object
template: field declarations and method definitions Object,String,Random,Scanner,Integer Instance/Object allocation of memory for a specific one new String("hello") new Integer(3) new Scanner( System.in)

8 ArrayList Is a Data Structure Similar to an array
holds elements of same data type elements contiguous in memory index starts at 0 Different from an array grows automatically only works with reference types Essentially, manages an oversize array

9 Inside ArrayList package java.util;
In java.util package Ultimately, extends from Object package java.util; class ArrayList<E> extends AbstractList<E> { int size; Object [] elementData; boolean add(E e) { … } void add(int index, E e) { … } } Fields are variables declared in a class but outside methods Methods access the fields

10 Java Source Code Usually within Java Development Kit (JDK).
C:\Program Files\AdoptOpenJDK\jdk hotspot Look for src.zip Since java.util.ArrayList look in java\util\ for ArrayList.java API created from source JavaDoc comments

11 TopHat: Path to Scanner
In source code folder, what path would you look to find Scanner.java?

12 Creating an ArrayList Import import java.util.ArrayList; Declaration
ArrayList<RefType> varName; Allocation/Instantiation varName = new ArrayList<RefType>(); Any reference type, but not primitive type.

13 Recall Primitive Wrapper Classes
Primitive Data Type Primitive 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

14 TopHat: ArrayList Element Type
Which of the following Cannot be used as the datatype of an element in an ArrayList? String int Random Double Object

15 Constructor A special method only called once when initially creating an instance/object. Called to initialize fields of instance/object, after memory for instance/object is allocated.

16 ArrayList Constructors
Special methods to initialize instances ArrayList<RefType>() //default capacity of 10 ArrayList<RefType>( int initialCapacity) If you know how many items will be added then set as the initialCapacity. Otherwise, when growing the ArrayList has to create a new array, guessing at length, and copy elements over.

17 Declare and Allocate ArrayLists
Separate declaration from instantiation ArrayList<String> names; names = new ArrayList<String>(100); ArrayList<Double> nums = new ArrayList<>(5); ArrayList<int> nums2; //won't compile Initial capacity <> is abbreviation since in declaration statement Use primitive wrapper class, Integer.

18 Memory: Internal View in main method ArrayList<Integer> nums;
nums = new ArrayList<Integer>(4); Initial capacity items added size elementData null nums On heap, size and elementData are together On stack, in main stack frame

19 Draw an Internal Diagram
What does internal view of memory look like? ArrayList<Integer> nums; nums = new ArrayList<Integer>(1); nums.add( 5 ); nums.add( 4 );

20 Memory: Internal View in main method ArrayList<Integer> nums;
nums = new ArrayList<Integer>(1); nums.add( 5 ); nums.add( 4 ); Grows automatically size 2 5 elementData 4 nums

21 Memory: External View Internally an array of size 20 is already allocated in anticipation of growth. in main method ArrayList<Integer> nums; nums = new ArrayList<Integer>(20); nums.add( 5 ); nums.add( 4 ); 5 4 nums

22 TopHat: How much memory?
ArrayList<Double> nums; for reference for reference to and instance of ArrayList for reference, instance of ArrayList, and items in ArrayList error Just enough for a reference, there is not an instance of ArrayList allocated and there aren't any items allocated.

23 TopHat: How much memory?
ArrayList<Double> nums; nums = new ArrayList<Double>(5); for reference reference and instance of ArrayList reference, instance of ArrayList, and 5 items in ArrayList error

24 TopHat: How much memory?
ArrayList<Double> nums; nums = new ArrayList<Double>(); nums.add( 12.3 ); for reference reference and instance of ArrayList reference, instance of ArrayList, and 1 Double error

25 Appending to an ArrayList
Initial capacity ArrayList<Double> nums; nums = new ArrayList<Double>(3); nums.add(1.0); nums.add(new Double(2.0)); nums.add(3.0); nums.add(4.0); System.out.print(nums.size()); Grows automatically size is number of items in ArrayList, Not capacity import java.util.ArrayList; public class ClassNameHere { public static void main(String[] args) { ArrayList<Double> nums; nums = new ArrayList<Double>(3); nums.add(1.0); nums.add(new Double(2.0)); nums.add(3.0); nums.add(4.0); System.out.print(nums.size()); }

26 TopHat: What will print out?
ArrayList<Double> nums; nums = new ArrayList<Double>(2); nums.add(1.0); nums.add(new Double(2.0)); nums.add(4.0); System.out.print(nums.size());

27 Create an ArrayList from an Array
Character [] charArray = {'a','b','c'}; ArrayList<Character> charList; charList= new ArrayList<Character>(); chars.addAll( java.util.Arrays.asList( charArray )); Returns a List that is then added to ArrayList.

28 Printing an ArrayList ArrayList<Character> chars;
Populate an ArrayList from an array ArrayList<Character> chars; chars = new ArrayList<Character>(); chars.addAll( java.util.Arrays.asList( new Character[]{'a','b','c'})); System.out.print( chars ); System.out.print( chars.toString() ); Both prints have same result, since print(Object) calls the toString method

29 Inserting into an ArrayList
Default initial capacity is 10 ArrayList<Character> chars; nums = new ArrayList<Character>(); nums.add('b'); nums.add(0, 'a'); nums.add(0, 'c'); System.out.print(nums.size()); System.out.print(nums); at index, insert a new element

30 TopHat: What will print out?
ArrayList<Integer> list; list = new ArrayList<Integer>(); list.add( 2); list.add(0,3); list.add(1,4); System.out.println( list);

31 Setting an Element in an ArrayList
ArrayList<Character> chars; nums = new ArrayList<Character>(3); nums.add('b'); nums.set(0, 'a'); nums.set(0, 'c'); System.out.print(nums.size()); System.out.print(nums); At index replace element

32 Removing an Element from ArrayList
ArrayList<Character> chars; nums = new ArrayList<Character>(3); nums.add('a'); nums.add('b'); nums.add('c'); nums.remove('a'); nums.remove( 1 ); System.out.print(nums.size()); System.out.print(nums); Removing by element or index Both shift elements down

33 TopHat: What will print out?
ArrayList<Integer> list; list = new ArrayList<Integer>(8); list.add(0,3); list.set(0,5); list.add(0,4); list.remove( 1); System.out.println( list);

34 (actual number of items)
Capacity vs Size Capacity (places available) Size (actual number of items) array .length attribute (for perfect size array this is also the number of items) separate variable of count of the items in array (e.g., for oversize array) ArrayList automatically increases when necessary .size() method

35 TopHat: What are size & capacity?
ArrayList<Character> chars; chars = new ArrayList<Character>(); chars.addAll( java.util.Arrays.asList( new Character[]{'a','b','c'})); size: 3 capacity: 10 size: 10 capacity: 3 size is the number of elements in the list from a user point of view capacity is the number of places in the internal array within the ArrayList

36 TopHat: Which is fastest?
void methodA( ArrayList<Integer> nums ) { nums.add( 0, 1); } void methodB( ArrayList<Integer> nums ) { nums.add( 1); methodB since it adds it to the end. methodA would have to move every element down one before inserting at the beginning

37 Other Common ArrayList Methods
get(int index) //return element at index clear() //remove all elements isEmpty() //whether it contains any elements

38 For Loop static void printList(ArrayList<Character> list) {
for ( int i = 0; i < list.size(); ++i) { System.out.println( list.get( i )); } import java.util.ArrayList; public class ClassNameHere { static void printList(ArrayList<Character> list) { for ( char ch : list ) System.out.println( ch ); } public static void main(String[] args) { ArrayList<Character> chars = new ArrayList<>(); chars.addAll( java.util.Arrays.asList( new Character[]{'a','b','c'})); printList( chars );

39 Enhanced For Loop Readable code to iterate through all items
Avoid out-of-bounds errors Doesn't have position information static void printList(ArrayList<Character> list) { for ( char ch : list ) System.out.println( ch ); } import java.util.ArrayList; public class ClassNameHere { static void printList(ArrayList<Character> list) { for ( char ch : list ) System.out.println( ch ); } public static void main(String[] args) { ArrayList<Character> chars = new ArrayList<>(); chars.addAll( java.util.Arrays.asList( new Character[]{'a','b','c'})); printList( chars );

40 Array vs ArrayList Array ArrayList Fixed size Yes No Grows dynamically
Primitive types Reference types Constant access time Arrays have a simpler syntax.

41 Is an Array or ArrayList better?
For a fixed size data structure such as a cave or game board? For reading in an unknown number of values from a user or a file? Array for a fixed size

42 Today Hours Spent in Last Week Due Chap 8 zyLabs
Code Refactor 1: Wumpus Caves

43 Multidimensional ArrayLists
ArrayLists of ArrayLists conceptually similar to arrays of arrays ArrayList<ArrayList<Integer>> table; table = new ArrayList<ArrayList<Integer>>(); table.add( new ArrayList<Integer>());

44 Draw Multidimensional ArrayLists
ArrayList<ArrayList<Integer>> table; table = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> row = new ArrayList<>(); row.add(4); row.add(5); table.add( row ); row.add(6);

45 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)); }

46 Draw a Diagram & TopHat [[],[],[]]
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.

47 TopHat: What is printed out?
ArrayList<Integer> list4; list4 = new ArrayList<Integer>(100); for ( int i = 0; i < 1000; i++) { list4.add( i); } System.out.println( list4.size());

48 TopHat: Write the code. 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?

49 TopHat: What size and elements?
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); 5 [A,B,C,D,E] 4 [B, A, D, E] 3 [B,D,E] error or other

50 Common Algorithms Searching Sorting Palindrome?

51 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. arr x */ public static int linearSearch( int arr[], int x) { for ( int i = 0; i < arr.length; i++) { if ( arr[i] == x) { return i; } return -1;

52 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;

53 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;


Download ppt "CS 200 Objects and ArrayList"

Similar presentations


Ads by Google