ACSA Exam Prep
Unit 4 · Data Collections · Topic 4.8

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.

Learning objectives
  • 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.

Code
ArrayList<String> names = new ArrayList<String>();
System.out.println(names.size());
Output
0

The six methods

MethodDoesReturns
size()Number of elementsint
add(obj)Appends to the endtrue
add(i, obj)Inserts at i, shifting later elements right (0 ≤ i ≤ size)nothing
get(i)Element at ithe element
set(i, obj)Replaces element at ithe old element
remove(i)Removes element at i, shifting later elements leftthe removed element

Tracing a sequence of calls

Code
ArrayList<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.

Code
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
Key points
  • An ArrayList resizes itself and holds object references.
  • new ArrayList<E>() creates an empty list; E lets the compiler catch type errors.
  • In java.util; needs an import.
  • Indexes run 0 to size() - 1.
Watch out
  • add(size(), x) is legal (appends); add(size() + 1, x) throws.
  • set and remove both return the element that was there before.
  • Printing an ArrayList shows [a, b, c].
Quick check
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.