Lesson 14 of 23

In progress

Course progress

Java

ArrayList and the List interface

Use a growable list, choose between ArrayList and LinkedList, and avoid the concurrent-modification exception when removing items.

An array has a fixed length. Most real programs do not know how many items they will hold, so the collections library provides lists that grow.

What you will learn

  • Create and manipulate an ArrayList.
  • Declare variables as List rather than the implementation.
  • Remove items safely while iterating.

The basics

import java.util.ArrayList;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Ravi");
names.add(1, "Meera");          // insert at index
System.out.println(names);      // [Ana, Meera, Ravi]
System.out.println(names.get(0));      // Ana
System.out.println(names.size());      // 3
System.out.println(names.contains("Ravi")); // true
names.set(0, "Ananya");         // replace
names.remove("Meera");          // remove by value
System.out.println(names);      // [Ananya, Ravi]
}
}

List is the interface; ArrayList is the implementation. Declaring the variable as List means the code depends on the contract, and switching to another implementation touches one line.

get takes an index, set replaces at an index, remove has two overloads: remove(int index) removes by position, remove(Object value) removes by value. With a List<Integer>, remove(1) removes the element at index 1, not the value 1 — use remove(Integer.valueOf(1)) for the value.

Iterating

for (String name : names) {
System.out.println(name);
}
names.forEach(name -> System.out.println(name.toUpperCase()));
for (int i = 0; i < names.size(); i++) {
System.out.println(i + ": " + names.get(i));
}

The enhanced loop and forEach are for reading. The index loop is for when the position matters.

Removing while iterating

List<String> names = new ArrayList<>(List.of("Ana", "", "Ravi", " "));
// Throws ConcurrentModificationException
// for (String name : names) {
//     if (name.isBlank()) names.remove(name);
// }
names.removeIf(String::isBlank);
System.out.println(names);   // [Ana, Ravi]

Modifying a list while an iterator is walking it invalidates the iterator, and the next step throws ConcurrentModificationException. removeIf is the correct tool: it does the removal in one pass and knows about the iterator.

If you need more complex logic, use an explicit iterator:

var it = names.iterator();
while (it.hasNext()) {
if (it.next().length() > 10) {
it.remove();
}
}

Removing by index while iterating forwards also skips elements, because everything after the removed index shifts left. Iterate backwards if you must use indexes.

Choosing an implementation

  • ArrayList — backed by an array, fast random access, fast append, slow insert or remove in the middle.
  • LinkedList — a doubly linked list, fast insert and remove at the ends, slow random access.

In practice, ArrayList is the right default. It is faster for iteration and lookup, uses less memory per element, and the cases where LinkedList wins are narrow. Modern JVMs make the theoretical arguments weaker than they look.

If you need a queue, use ArrayDeque rather than LinkedList; it is faster for both ends and does not carry the list overhead.

Useful methods

List<Integer> numbers = new ArrayList<>(List.of(5, 2, 9));
numbers.sort(Integer::compareTo);        // [2, 5, 9]
System.out.println(numbers.indexOf(9));  // 2
System.out.println(numbers.isEmpty());   // false
numbers.clear();
System.out.println(numbers.size());      // 0

List.of(...) creates an immutable list, which is excellent for constants and test data. Passing it to new ArrayList<>(...) makes a mutable copy, which is the common pattern when you need to modify it.

Collections.sort is the legacy form; list.sort(comparator) is the modern one.

Lists of primitives

Generics cannot hold primitives, so List<int> is illegal. Use the wrapper:

List<Integer> counts = new ArrayList<>();
counts.add(1);                 // autoboxed
int first = counts.get(0);     // unboxed

That costs an object per element and a null risk on unboxing. For large numeric data, an int[] or a specialised structure avoids the boxing, which is why arrays still matter.

Views and immutability

subList returns a view, not a copy: changes to the view write through to the original list. That is efficient and surprising.

List<String> names = new ArrayList<>(List.of("Ana", "Ravi", "Meera", "Sam"));
List<String> middle = names.subList(1, 3);
middle.clear();
System.out.println(names);   // [Ana, Sam]

That is useful for bulk operations on a range and dangerous when a caller keeps the view after the original changes. Copy it with new ArrayList<>(names.subList(1, 3)) if it must outlive the operation.

List.of and List.copyOf produce immutable lists that throw on any modification. Returning one from a method is the simplest way to stop a caller from changing your state, and it removes a whole class of bugs from code that shares collections between objects.

List equality and copying

List<String> a = List.of("x", "y");
List<String> b = new ArrayList<>(a);
System.out.println(a.equals(b));    // true, content is compared
System.out.println(a == b);         // false

List implementations define equals by content and order, so two lists with the same elements in the same order are equal. That is different from arrays, which compare by reference unless you use Arrays.equals.

new ArrayList<>(other) is a shallow copy: the list structure is new, the elements are shared.

Calling remove(2) on a List<Integer> expecting to remove the value 2. It removes the element at index 2, or throws if the list is shorter.

Build a list of five prices, remove every price below 10000 paise with removeIf, sort the rest descending, and print the total.

Show solution
import java.util.ArrayList; import java.util.List; public class Prices { public static void main(String[] args) { List<Long> prices = new ArrayList<>(List.of(4_500L, 32_000L, 12_000L, 9_900L, 120_000L)); prices.removeIf(price -> price < 10_000L); prices.sort((a, b) -> Long.compare(b, a)); long total = 0; for (long price : prices) { total += price; } System.out.println(prices); System.out.println("total: " + total / 100.0); } }

removeIf avoids the concurrent-modification problem. The comparator (a, b) -> Long.compare(b, a) reverses the natural order, and the sum stays in long until the display conversion.

Recap

  • Declare List, instantiate ArrayList, and prefer List.of for fixed data.
  • removeIf and explicit iterators are the safe ways to remove while walking a list.
  • ArrayList is the default; use ArrayDeque for queues and arrays for bulk primitives.

Next, HashMap: keyed lookup in constant time.

What is the initial capacity of an ArrayList?
Ten by default, growing by about half each time. Pass a capacity when you know the size to avoid repeated copies.
Is List.of modifiable?
No. It throws `UnsupportedOperationException` on add or remove, which is why it is safe to share.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.