80 likes | 92 Views
Learn about the disadvantages of using arrays in programming and how ArrayList can help manage array size and implement common operations. Declare and use an ArrayList, access elements with get and set methods, and understand key points and algorithms for ArrayList.
E N D
COM S 207 ArrayList Instructor: Ying Cai Department of Computer Science Iowa State University yingcai@iastate.edu
Disadvantages of Array • When writing a program that collects values, we don’t always know how many values we will have • We will have to manage the size of an array, and the valid length (i.e., lastIndex) ourselves • We need to implement operations such as insert and remove ourselves
ArrayList • Array lists can grow and shrink as needed • The ArrayList class supplies methods for common tasks, such as inserting and removing elements • import java.util.ArrayList
Declare and Use an ArrayList An array list object of size 0 Variable name Variable type ArrayList<String> friends = new ArrayList<String>(); friends.add(“Cindy”); friends.add(“Scott”); String name = friends.get(1); friends.set(0, “Harry”); The add method appends an element to the array list Use get and set methods to access an element Note: For now, use ArrayList only to store String. You cannot add an primitive type of data (etc., int, double)
Some Key Points • ArrayList must be initialized before use • When the ArrayList<String> is initialized, the size of the array is 0 • The size increases when you add an object, decreases when you remove an object • The last valid index is names.size()-1 • As with arrays, it is an error to access a nonexistent element ArrayList<String> names; names.add(“Harry”); // Error! int i = names.size(); String name = names.get (i); // Error!
Some Key Points • To set an array list element to a new value, use the set method • You can insert an element in the middle of an array list // overwrite the element at position 2 names.set(2, “John”); // add a new element at position 1 // and moves all elements with index // 1 or larger by one position names.add(1, “Scott”);
Some Algorithms // visit all elements of an array list for (int i=0; i<names.size(); i++) { String name = names.get(i); System.out.println(name); } // copy an array list ArrayList<String> newNames = newArrayList<String>(names); // reverse the names list in reverse order, and store // starting with the last element and store ArrayList<String> reversed = new ArrayList<String>(); for (int i=names.size()-1; i>=0; i--) { reversed.add(names.get(i)); }
Exercise What does the array list names contain after the following statements? ArrayList<String> names = new ArrayList<String>; names.add(“Bob”); names.add(0, “Ann); names.remove(1); names.add(“Cal”);