ArrayList: add, get, set, remove
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)An ArrayList is a list that grows and shrinks by itself. It keeps items in the order you add them, allows duplicates, and lets you reach any item by its index, just like an array.
Create an ArrayList
A List is an ordered collection: items keep the order you add them in, can repeat, and are reached by position. ArrayList is the most-used List class; it keeps its items in a resizable array and grows and shrinks by itself.
ArrayList lives in the java.util package. Write the variable type as the interface and the object as the class: List<String> names = new ArrayList<>();. This is programming to the interface, from the previous module.
Example 1 · Your first ArrayList: an online cart
import java.util.ArrayList;import java.util.List;
public class CartDemo { public static void main(String[] args) { List<String> cart = new ArrayList<>(); System.out.println("Empty? " + cart.isEmpty());
cart.add("Laptop"); cart.add("Mouse"); cart.add("Keyboard"); cart.add("Mouse");
System.out.println("Cart: " + cart); System.out.println("Items: " + cart.size()); System.out.println("First: " + cart.get(0)); System.out.println("Last: " + cart.get(cart.size() - 1)); System.out.println("Empty? " + cart.isEmpty()); }}Empty? true Cart: [Laptop, Mouse, Keyboard, Mouse] Items: 4 First: Laptop Last: Mouse Empty? false
What this code does
- The list keeps the order of the
addcalls and allows the duplicateMouse. - The last item is always at
size() - 1; here that is index 3. println(cart)uses the list'stoString(), which prints every item in brackets.
The type in angle brackets is the element type: what the list holds. A list holds objects only, so numbers use wrapper types: List<Integer>, List<Double>, never List<int>. Java wraps an int into an Integer when you add it (autoboxing) and unwraps it when you read it into an int (unboxing).
A new list is empty. Printing a list shows its items in square brackets, like [Laptop, Mouse], because ArrayList overrides toString().
new ArrayList<>(List.of(4, 7, 1)). The Fixed and unmodifiable lists lesson explains List.of itself.Add and read items
An index is the position number of an item in a list. The first item has index 0 and the last has index size() - 1, so a list with 3 items has the indexes 0, 1 and 2.
add(item) puts an item at the end. add(index, item) puts it at that position and moves every later item one place to the right. Nothing is overwritten.
import java.util.*;
public class AddAndRead { public static void main(String[] args) { List<Integer> marks = new ArrayList<>(); marks.add(72); marks.add(85); marks.add(1, 60); System.out.println(marks); System.out.println(marks.get(0) + " " + marks.get(marks.size() - 1)); System.out.println(marks.size() + " " + marks.isEmpty()); }}[72, 60, 85] 72 85 3 false
get(index) reads one item. As with arrays, the first index is 0 and the last is size() - 1. Note that size() is a method with brackets, not the length field of an array.
add(e)→ adds at the endadd(i, e)→ inserts at indexi, later items move rightget(i)→ returns the item at indexisize()/isEmpty()→ number of items /truewhen there are none
Change and remove items
set(index, item) replaces the item at an index and returns the old item; the size stays the same. remove has two forms: remove(int index) removes by position, remove(Object o) removes the first equal item.
Example 2 · Insert, replace and remove marks
import java.util.ArrayList;import java.util.List;
public class MarksListDemo { public static void main(String[] args) { List<Integer> marks = new ArrayList<>(); marks.add(78); marks.add(64); marks.add(91); System.out.println("Marks: " + marks);
marks.add(1, 85); System.out.println("After late entry at index 1: " + marks);
int old = marks.set(2, 70); System.out.println("Re-evaluation: " + old + " -> " + marks.get(2));
int removed = marks.remove(0); System.out.println("Removed " + removed + ": " + marks);
int total = 0; for (int i = 0; i < marks.size(); i++) { total = total + marks.get(i); } System.out.println("Total " + total + ", average " + (total / marks.size())); }}Marks: [78, 64, 91] After late entry at index 1: [78, 85, 64, 91] Re-evaluation: 64 -> 70 Removed 78: [85, 70, 91] Total 246, average 82
What this code does
add(1, 85)pushes 64 and 91 one place right, so 64 moves to index 2.setreturns the old value (64), andremove(0)returns the removed value (78). Both are unboxed intoint.- Loop from
0tosize() - 1and useget(i), the same way you loop over an array.
remove(int index) returns the removed item. remove(Object o) returns true, or false when there is no such item. After any remove, later items move one place to the left, so their indexes go down by one. clear() removes everything.
The remove(int) trap with Integer lists
With a List<Integer>, what does absent.remove(1) mean: the item at index 1, or the value 1? Java first looks for a method that fits without boxing, so remove(int index) wins.
Example 3 · Bug: remove(1) removes an index, not a value
import java.util.ArrayList;import java.util.List;
public class AbsentBugDemo { public static void main(String[] args) { List<Integer> absent = new ArrayList<>(List.of(4, 7, 1, 12)); System.out.println("Absent rolls: " + absent);
// Roll number 1 arrived late. Take roll 1 off the list. absent.remove(1);
System.out.println("After removing roll 1: " + absent); }}Absent rolls: [4, 7, 1, 12] After removing roll 1: [4, 1, 12]
What this code does
1is anint, so Java callsremove(int index)and removes the item at index 1, which is roll 7.- Roll 1 is still marked absent and roll 7 is lost. No error, no warning: only the output shows the bug.
Example 4 · Fix: remove the value with Integer.valueOf
import java.util.ArrayList;import java.util.List;
public class AbsentFixDemo { public static void main(String[] args) { List<Integer> absent = new ArrayList<>(List.of(4, 7, 1, 12));
boolean found = absent.remove(Integer.valueOf(1)); System.out.println("Removed roll 1? " + found + " -> " + absent);
boolean again = absent.remove(Integer.valueOf(1)); System.out.println("Removed roll 1 again? " + again + " -> " + absent);
int atIndex = absent.remove(1); System.out.println("Removed index 1 (roll " + atIndex + ") -> " + absent); }}Removed roll 1? true -> [4, 7, 12] Removed roll 1 again? false -> [4, 7, 12] Removed index 1 (roll 7) -> [4, 12]
What this code does
Integer.valueOf(1)is an object, so onlyremove(Object)fits. It removes the value 1 and returnstrue.- The second call finds no 1 and returns
false; the list does not change and nothing crashes. remove(int)returns the removed item itself, so you can print which roll left the list.
To remove the value, pass an Integer object: absent.remove(Integer.valueOf(1)). Now only remove(Object) fits.
This bug compiles without a warning. It either removes the wrong item silently, or crashes when the value is larger than the list.
Predict the output
remove: index or value?
Read each snippet and pick what it prints.
Round 1 of 4
Product ids in a list. Remove with the number 1.
Index errors
get, set and remove(int) accept indexes from 0 to size() - 1. Any other index throws IndexOutOfBoundsException, with a message like Index 3 out of bounds for length 3.
Example 5 · Crash: reading past the end
import java.util.ArrayList;import java.util.List;
public class ToppersDemo { public static void main(String[] args) { List<String> toppers = new ArrayList<>(); toppers.add("Kavya"); toppers.add("Rohan"); toppers.add("Meera");
System.out.println("Toppers: " + toppers.size()); System.out.println("Third topper: " + toppers.get(3)); }}Toppers: 3 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106) at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302) at java.base/java.util.Objects.checkIndex(Objects.java:385) at java.base/java.util.ArrayList.get(ArrayList.java:427) at ToppersDemo.main(ToppersDemo.java:12)
What this code does
- Three items means indexes 0, 1 and 2. "Third" is
get(2);get(3)is outside the list. - The message
Index 3 out of bounds for length 3names both numbers. The last line of the trace,ToppersDemo.java:12, points at your code. - The
java.base/...lines are inside Java's own classes. Their line numbers differ between Java versions.
add(index, item) also accepts size(), which means "at the end". A list has no empty slots: a list of size 3 has exactly the indexes 0, 1 and 2, nothing more.
Check size() or isEmpty() before you read the first or last item.
Example 6 · A hostel room waiting list
import java.util.ArrayList;import java.util.List;
public class HostelWaitingListDemo { public static void main(String[] args) { List<String> waiting = new ArrayList<>(); waiting.add("Aarav"); waiting.add("Diya"); waiting.add("Kabir"); waiting.add(0, "Sneha"); System.out.println("Waiting: " + waiting);
boolean diyaLeft = waiting.remove("Diya"); boolean rahulLeft = waiting.remove("Rahul"); System.out.println("Diya cancelled: " + diyaLeft); System.out.println("Rahul cancelled: " + rahulLeft);
String first = waiting.remove(0); String second = waiting.remove(0); System.out.println("Room 101: " + first); System.out.println("Room 102: " + second);
System.out.println("Still waiting: " + waiting + ", count " + waiting.size()); if (!waiting.isEmpty()) { System.out.println("Next in line: " + waiting.get(0)); } }}Waiting: [Sneha, Aarav, Diya, Kabir] Diya cancelled: true Rahul cancelled: false Room 101: Sneha Room 102: Aarav Still waiting: [Kabir], count 1 Next in line: Kabir
What this code does
add(0, "Sneha")puts a priority case at the front of the line.remove("Diya")returnstrue;remove("Rahul")returnsfalsebecause Rahul was never on the list.remove(0)twice takes the first person each time, because the rest move left after every remove.
Next step
Check your understanding
12 quick questions