ArrayList Methods
Skill 2.BSkill 3.BSkill 3.D
Big idea: An ArrayList is a resizable list of objects. Adding or removing in the middle shifts the later elements, which changes their indexes.
- Develop code for collections of related objects using ArrayList objects and determine the result of calling methods on these objects.
Creating a list
ArrayList is in java.util. The type in angle brackets says what it holds, and the compiler rejects anything else. A new list is empty: size() is 0.
ArrayList<String> names = new ArrayList<String>();
System.out.println(names.size());Output0The six methods
| Method | Does | Returns |
|---|---|---|
size() | Number of elements | int |
add(obj) | Appends to the end | true |
add(i, obj) | Inserts at i, shifting later elements right (0 ≤ i ≤ size) | nothing |
get(i) | Element at i | the element |
set(i, obj) | Replaces element at i | the old element |
remove(i) | Removes element at i, shifting later elements left | the removed element |
Tracing a sequence of calls
CodeArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add(1, "X");
System.out.println(list);
String old = list.set(2, "Y");
System.out.println(old + " " + list);
String gone = list.remove(0);
System.out.println(gone + " " + list + " " + list.size());Output[A, X, B, C] B [A, X, Y, C] A [X, Y, C] 3
Index errors
Valid indexes for get, set, and remove are 0 to size() - 1. add(i, obj) also allows i == size() (appending). Anything else throws IndexOutOfBoundsException.
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(5);
nums.add(nums.size(), 9);
System.out.println(nums);
nums.get(2);Output[5, 9] throws IndexOutOfBoundsException
- An
ArrayListresizes itself and holds object references. new ArrayList<E>()creates an empty list;Elets the compiler catch type errors.- In
java.util; needs an import. - Indexes run 0 to
size() - 1.
add(size(), x)is legal (appends);add(size() + 1, x)throws.setandremoveboth return the element that was there before.- Printing an ArrayList shows
[a, b, c].
list is [10, 20, 30]. After list.add(0, 5); list.remove(2); what is list?
Show answer
[5, 10, 30]. Insert gives [5, 10, 20, 30], then index 2 (20) is removed.