TOPIC 4.8 · STUDY

ArrayList Methods

ArrayList is a resizable list from java.util. You build it empty, append or insert with add, read with get, replace with set, delete with remove, and ask size() for the count. Valid indexes run from 0 through size() - 1.

4.8.A

ArrayList methods

An ArrayList holds a sequence of object references and can grow or shrink. Import the class, then construct an empty list. After ArrayList<String> tags = new ArrayList<String>(); the list has no elements, so tags.size() is 0. There is no length field on an ArrayList; you call the size() method.

import java.util.ArrayList;
ArrayList<String> tags = new ArrayList<String>();
System.out.print(tags.size());
tags.add("mint");
tags.add("coral");
tags.add(1, "ivory");
System.out.print(tags.get(0) + "," + tags.get(1) + "," + tags.get(2));
String was = tags.set(2, "sage");
String gone = tags.remove(0);
System.out.print(was + "," + gone + "," + tags.size());

add("mint") and add("coral") append at the end, so the list is mint then coral and size is 2. add(1, "ivory") inserts at index 1 and shifts coral one place right, yielding mint, ivory, coral. get(index) returns the element at that index. set(2, "sage") replaces coral with sage and returns the old value coral; size stays the same. remove(0) deletes mint, shifts the rest left, and returns mint; size becomes 2. Valid indexes always run from 0 through size() - 1.

Method Effect
add(value) Appends value at the end; size grows by 1
add(index, value) Inserts at index; later items shift right
get(index) Returns the element at index
set(index, value) Replaces the element; returns the old value
remove(index) Deletes at index; later items shift left; returns the removed value
size() Returns how many elements are stored

Insertion shifts matter on the exam. After add("red"), add("navy"), and add(1, "gold"), gold sits at index 1 and navy moves to index 2.

Three cells left to right after add("red"), add("navy"), add(1, "gold"): red, gold, navy.

add(1, "gold") inserts between red and navy; navy shifts from index 1 to index 2.

Key points

  • import java.util.ArrayList; then new ArrayList<String>() starts empty with size 0.
  • add(value) appends; add(index, value) inserts and shifts later items right.
  • get(index) reads; set(index, value) replaces and returns the old element.
  • remove(index) deletes, shifts left, and returns the removed element.
  • size() is the count; valid indexes are 0 through size() - 1.

size() is a method call. Arrays use the length field; ArrayList has no length field.

Practice this topic