Download presentation
Presentation is loading. Please wait.
Published byPaul Shelton Modified over 9 years ago
1
COM S 207 ArrayList Instructor: Ying Cai Department of Computer Science Iowa State University yingcai@iastate.edu
2
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
3
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
4
Declare and Use an ArrayList ArrayList friends = new ArrayList (); friends.add(“Cindy”); friends.add(“Scott”); String name = friends.get(1); friends.set(0, “Harry”); Variable type Variable name An array list object of size 0 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)
5
Some Key Points ArrayList must be initialized before use When the ArrayList 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 names; names.add(“Harry”); // Error! int i = names.size(); String name = names.get (i); // Error!
6
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”);
7
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 newNames = newArrayList (names); // reverse the names list in reverse order, and store // starting with the last element and store ArrayList reversed = new ArrayList (); for (int i=names.size()-1; i>=0; i--) { reversed.add(names.get(i)); }
8
Exercise What does the array list names contain after the following statements? ArrayList names = new ArrayList ; names.add(“Bob”); names.add(0, “Ann); names.remove(1); names.add(“Cal”);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.