Java ArrayList: The Stretchy Array
add, add at an index, get, set, remove and contains on a list of courses and a cart, why Git at index 1 pushes SQL and Spring right, removing scores below 50 with an Iterator or removeIf, List.of that can't change, and the array inside that grows from 10 to 15.
What you will learn
- Add, insert, read, replace and remove items in an ArrayList
- Explain why inserting or removing shifts the cells after it
- Loop over a list and remove items safely with an Iterator or removeIf
- Tell a fixed List.of list from a growing ArrayList, and how an ArrayList grows
Before you start
- From arrays to collections: the framework map
- Java wrapper classes and autoboxing
An ArrayList is a list that grows as you add to it, which is why it's often called the stretchy array. You don't need to memorise its methods (an AI can write the syntax for you), but you do need to know what each one does.
Add to it, read from it
package org.studyeasy.s04l03;
import java.util.ArrayList;
import java.util.List;
public class Ex01_AddAndGet {
public static void main(String[] args) {
List<String> courses = new ArrayList<>();
courses.add("Java"); // goes to the end
courses.add("SQL");
courses.add("Spring");
courses.add(1, "Git"); // squeezes in at index 1
System.out.println(courses);
System.out.println("First: " + courses.get(0));
System.out.println("Size: " + courses.size());
}
}
[Java, Git, SQL, Spring]
First: Java
Size: 4
add(value) puts the value at the end; add(1, "Git") squeezes it in at index 1. get(0) reads the first item and size() counts them. This list is for Strings only, so courses.add(42) is an incompatible types error.
Change it, search it
List<String> cart = new ArrayList<>();
cart.add("Pen");
cart.add("Notebook");
cart.add("Bag");
cart.add("Ruler");
cart.set(0, "Marker"); // replace what is at index 0
cart.remove(2); // remove by index: Bag
cart.remove("Ruler"); // remove by value
System.out.println(cart);
System.out.println("Notebook? " + cart.contains("Notebook"));
System.out.println("Bag? " + cart.contains("Bag"));
[Marker, Notebook]
Notebook? true
Bag? false
set overwrites a cell in place. remove works two ways: remove(2) takes out whatever is at index 2 (the Bag) and Ruler moves one cell left; remove("Ruler") finds the value and takes it out. The list closes the gap every time, so there are never holes in the indexes. contains answers true or false. cart.remove(10) throws IndexOutOfBoundsException.
Walk the list two ways
List<Double> prices = new ArrayList<>();
prices.add(12.5);
prices.add(40.0);
prices.add(7.25);
for (int i = 0; i < prices.size(); i++) { // need the index
System.out.println("Index " + i + ": " + prices.get(i));
}
double total = 0;
for (double price : prices) { // just the values
total += price;
}
System.out.println("Total: " + total);
Index 0: 12.5
Index 1: 40.0
Index 2: 7.25
Total: 59.75
Use the index loop when you need i; use for-each when you only need the values.
Fixed list, growing copy
List<String> weekdays = List.of("Mon", "Tue", "Wed"); // fixed
try {
weekdays.add("Thu");
} catch (UnsupportedOperationException e) {
System.out.println("List.of cannot change");
}
List<String> classDays = new ArrayList<>(weekdays); // a copy
classDays.add("Thu"); // grows
System.out.println(classDays);
List.of cannot change
[Mon, Tue, Wed, Thu]
List.of gives a fixed list: no add, remove or set. Passing it to new ArrayList<>(...) makes a copy, and the copy can change.
Remove while looping
List<Integer> scores =
new ArrayList<>(List.of(87, 42, 95, 38, 71));
Iterator<Integer> it = scores.iterator();
while (it.hasNext()) {
if (it.next() < 50) {
it.remove(); // the iterator removes it
}
}
System.out.println("Passed: " + scores);
Passed: [87, 95, 71]
An iterator is like a pointer that starts just before the first value. hasNext checks if there's another, next returns it, and remove deletes the one next just gave you. Calling scores.remove(s) inside a for-each instead makes the loop lose its place, and Java throws ConcurrentModificationException.
The same job in one call is removeIf. It takes a Predicate, an interface with one method that answers true or false for each element, here written as an anonymous class:
scores.removeIf(new Predicate<Integer>() {
public boolean test(Integer score) {
return score < 50; // true = remove it
}
});
It prints the same Passed: [87, 95, 71]. A lambda makes it shorter still.
An array inside, swapped when full
Inside, an ArrayList holds a plain array. Say it's full: capacity 10, ten names. Add Olivia and there's no free cell, so add calls an internal grow method. It makes a bigger array, the old length plus half of it (10 + 10/2 = 15), copies the ten names across and puts Olivia at index 10. Size is now 11 with four spare cells, and the old array is thrown away. Copying costs time, which is why it adds spare room instead of one cell at a time.
Recap
| Method | What it does |
|---|---|
add(v), add(i, v) | at the end, or squeezed in at i |
get(i), size() | read a cell, count items |
set(i, v) | replace in place |
remove(i), remove(v) | by index or by value; the rest move left |
contains(v) | true or false |
Iterator, removeIf | remove while looping |
List.of(...) | fixed; copy into an ArrayList to change it |
Next: LinkedList vs ArrayList.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java equals and hashCode: Why a HashSet Needs Both
== asks if it's the very same object, equals compares values, and hashCode puts equal objects in the same HashSet bucket. Three small programs show what breaks when hashCode is missing.
From Arrays to Collections: The Java Collections Framework Map
An array of 3 students can't seat John, so Java throws Index 3 out of bounds. A List just grows. Then the map of the framework: List, Set and Queue under Collection, Map beside it, four behaviours in one program, and why the variable type should be the interface.
Java Wrapper Classes and Autoboxing
List<int> won't compile because a list holds objects only. Integer.valueOf puts 87 in a box and intValue takes it out, and add and get do it for you. Then two traps: 128 == 128 is false, and unboxing a null Integer throws a NullPointerException.
Java LinkedList vs ArrayList: Nodes or an Array
An ArrayList is one block of cells; a LinkedList is a chain of nodes with next and prev links. Orders ORD-101 to ORD-106 show addFirst, getLast, removeFirst and remove(1), why get(2) walks two hops, and why a front insert moves three values in one and changes two links in the other.
