Java List Interface: ArrayList, LinkedList, Factory Methods and List Operations (OCP 21)
Lists for the OCP 21 exam: ArrayList versus LinkedList, Arrays.asList, List.of and List.copyOf, constructors, index-based methods, replaceAll, the overloaded remove trap, indexOf and lastIndexOf, IndexOutOfBoundsException, and converting lists to arrays.
kvi5hnuCode Sprout team member6 min readOn this page
A List is an ordered collection that allows duplicates. Every element has an int index, starting at 0, like an array. Unlike an array, most lists grow and shrink as you add and remove elements. When you aren't sure which collection to use, a list is usually the answer.
ArrayList versus LinkedList
The exam expects you to know two List classes:
ArrayList | LinkedList | |
|---|---|---|
| Structure | resizable array | doubly linked nodes |
get(i) / set(i, …) | constant time | linear time (walks the links) |
| add or remove at the ends | fast at the end | fast at both ends |
| Also implements | — | Deque (queue and stack methods) |
| Typical choice | the default list | when you need list and deque behavior together |
ArrayList is the right default. LinkedList mainly matters on the exam because it's both a List and a Deque (article 54). Both classes behave identically through the List interface, only their performance differs.
Creating lists
Constructors
var a = new ArrayList<String>(); // empty
var b = new ArrayList<String>(a); // copy of another collection
var c = new ArrayList<String>(20); // empty, with room for 20 before resizing
var d = new LinkedList<String>(b); // LinkedList has the first two forms only
The int constructor sets the initial capacity, not the size. c.size() is 0, and c.get(0) throws IndexOutOfBoundsException. LinkedList has no capacity constructor, so new LinkedList<String>(10) doesn't compile.
Factory methods
Three static methods create a list in one line, and they behave quite differently:
| Method | Result | set | add/remove | null elements | Linked to the source? |
|---|---|---|---|---|---|
Arrays.asList(T...) | fixed-size view of an array | allowed | UnsupportedOperationException | allowed | yes, both ways |
List.of(E...) | unmodifiable list | UnsupportedOperationException | UnsupportedOperationException | NullPointerException | no (copy) |
List.copyOf(Collection) | unmodifiable copy | UnsupportedOperationException | UnsupportedOperationException | NullPointerException | no (copy) |

String[] source = {"red", "green", "blue"};
List<String> backed = Arrays.asList(source);
List<String> listOf = List.of(source);
List<String> copyOf = List.copyOf(backed);
source[0] = "pink"; // the asList view sees this
backed.set(2, "navy"); // and the array sees this
System.out.println(Arrays.toString(source)); // [pink, green, navy]
System.out.println(backed); // [pink, green, navy]
System.out.println(listOf + " " + copyOf); // [red, green, blue] [red, green, blue]
backed.add("gold"); // UnsupportedOperationException: fixed size
listOf.set(0, "gold"); // UnsupportedOperationException
Two more details:
Arrays.asList(new int[] {1, 2})gives aList<int[]>with one element, because generics can't hold primitives.Arrays.asList(1, 2)autoboxes and givesList<Integer>.List.copyOfthrowsNullPointerExceptionif the source containsnull. If the source is already an unmodifiable list, it may return the same object.
List methods
On top of the Collection methods, List adds index-based operations:
| Method | Description |
|---|---|
void add(int index, E e) | inserts at index, shifting later elements right |
E get(int index) | returns the element at index |
E set(int index, E e) | replaces the element and returns the old one |
E remove(int index) | removes at index, shifting later elements left, and returns it |
int indexOf(Object o) / lastIndexOf(Object o) | first or last position of an equal element, or -1 |
void replaceAll(UnaryOperator<E> op) | replaces every element with op's result |
void sort(Comparator<? super E> c) | sorts in place (article 56) |
List<String> playlist = new ArrayList<>();
playlist.add("Intro"); // [Intro]
playlist.add("Outro"); // [Intro, Outro]
playlist.add(1, "Chorus"); // [Intro, Chorus, Outro]
String old = playlist.set(2, "End"); // old = "Outro" -> [Intro, Chorus, End]
playlist.remove("Intro"); // [Chorus, End]
playlist.remove(0); // [End]
playlist.replaceAll(String::toUpperCase); // [END]
Index rules
get,setandremove(int)need an existing index,0tosize() - 1. On an empty list, evenset(0, …)throwsIndexOutOfBoundsException.add(int, E)also acceptssize()itself, which appends at the end.add(1, "x")on an empty list throws.
The overloaded remove
List has two remove methods: remove(int index) from List and remove(Object o) from Collection. With a List<Integer>, the argument's type decides which one runs:
var ratings = new LinkedList<Integer>(List.of(5, 3, 1));
ratings.remove(1); // int -> removes INDEX 1 -> [5, 1]
ratings.remove(Integer.valueOf(1)); // Integer -> removes VALUE 1 -> [5]
An int argument matches remove(int) exactly, so no boxing happens. Two more consequences:
remove(Integer.valueOf(100))returnsfalsewhen the value isn't present, whileremove(100)throwsIndexOutOfBoundsException.- A
charwidens toint, so on aList<Character>,list.remove('a')tries to remove index 97.
Searching
indexOf and lastIndexOf use equals, just like the String methods with the same names:
var birds = List.of("owl", "jay", "owl", "wren");
birds.indexOf("owl"); // 0
birds.lastIndexOf("owl"); // 2
birds.indexOf("crow"); // -1
For large sorted lists, Collections.binarySearch is faster (article 56).
Converting a list to an array
List<String> names = new ArrayList<>(List.of("Ana", "Bo"));
Object[] objs = names.toArray(); // always Object[]
String[] strs = names.toArray(new String[0]); // typed array of the right size
String[] alt = names.toArray(String[]::new); // same, using a generator
names.clear();
System.out.println(strs.length); // 2: the array is an independent copy
If the array you pass is big enough, it's filled and returned, and the slot right after the last element is set to null. Otherwise a new array of the right size is created. Passing new String[0] is the common idiom. The opposite conversion, array to list, uses Arrays.asList or List.of.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Java 21 added
getFirst,getLast,addFirst,addLast,removeFirst,removeLastandreversedtoList(article 57). On 1Z0-830 they're current API. VectorandStackare legacy synchronized classes. UseArrayListandArrayDequeinstead.
Exam traps from this article
A complete example
A playlist shows insertion, replacement, searching and replaceAll. A LinkedList<Integer> demonstrates the two remove methods, and the three factory methods are compared side by side, including which operations throw.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Solution {
static void attempt(String label, Runnable action) {
try {
action.run();
System.out.println(label + ": ok");
} catch (RuntimeException e) {
System.out.println(label + ": " + e.getClass().getSimpleName());
}
}
public static void main(String[] args) {
// Index-based operations on an ArrayList
List<String> playlist = new ArrayList<>();
playlist.add("Intro"); // [Intro]
playlist.add("Outro"); // [Intro, Outro]
playlist.add(1, "Chorus"); // [Intro, Chorus, Outro]
String old = playlist.set(2, "Finale"); // returns the replaced element
playlist.add("Chorus");
System.out.println(playlist + " replaced " + old);
System.out.println("indexOf Chorus=" + playlist.indexOf("Chorus")
+ " lastIndexOf Chorus=" + playlist.lastIndexOf("Chorus")
+ " indexOf Bridge=" + playlist.indexOf("Bridge"));
playlist.replaceAll(String::toUpperCase);
System.out.println("replaceAll: " + playlist);
// remove(int index) versus remove(Object value)
List<Integer> ratings = new LinkedList<>(List.of(5, 3, 1, 3));
ratings.remove(1); // index 1 -> removes the first 3
ratings.remove(Integer.valueOf(1)); // value 1
System.out.println("ratings: " + ratings);
// Three factory methods and how they react to changes
String[] source = {"red", "green", "blue"};
List<String> backed = Arrays.asList(source);
List<String> listOf = List.of(source);
List<String> copyOf = List.copyOf(backed);
source[0] = "pink";
backed.set(2, "navy");
System.out.println("array=" + Arrays.toString(source) + " asList=" + backed
+ " List.of=" + listOf + " copyOf=" + copyOf);
attempt("asList.set", () -> backed.set(0, "gold"));
attempt("asList.add", () -> backed.add("gold"));
attempt("List.of.set", () -> listOf.set(0, "gold"));
attempt("copyOf.remove", () -> copyOf.remove(0));
attempt("get(9)", () -> playlist.get(9));
// List to array: the array is an independent copy
String[] snapshot = playlist.toArray(new String[0]);
playlist.clear();
System.out.println("snapshot " + snapshot.length + " " + Arrays.toString(snapshot) + ", list now " + playlist);
}
}
Output:
[Intro, Chorus, Finale, Chorus] replaced Outro
indexOf Chorus=1 lastIndexOf Chorus=3 indexOf Bridge=-1
replaceAll: [INTRO, CHORUS, FINALE, CHORUS]
ratings: [5, 3]
array=[pink, green, navy] asList=[pink, green, navy] List.of=[red, green, blue] copyOf=[red, green, blue]
asList.set: ok
asList.add: UnsupportedOperationException
List.of.set: UnsupportedOperationException
copyOf.remove: UnsupportedOperationException
get(9): IndexOutOfBoundsException
snapshot 4 [INTRO, CHORUS, FINALE, CHORUS], list now []
Points to notice:
set(2, "Finale")returnsOutro, the element it replaced.ratings.remove(1)removes the first3(at index 1), andremove(Integer.valueOf(1))removes the value1.- After
source[0] = "pink"andbacked.set(2, "navy"), the array and theasListview agree, while the two copies keep the original values. - Only
asList.setsucceeds. Every structural change on these lists throwsUnsupportedOperationException. toArray(new String[0])produces an independent copy that survivesplaylist.clear().
Common questions
Is Arrays.asList immutable?
No. It's fixed-size, but it's not unmodifiable: set and replaceAll work and write through to the array. Only operations that change the size fail.
When is LinkedList actually faster?
When you frequently add or remove at the front, or through an iterator in the middle. For most workloads, including indexed access, ArrayList wins thanks to its compact array.
How do I get a modifiable copy of List.of(...)?
Pass it to a constructor: new ArrayList<>(List.of("a", "b")).
Summary
- Lists are ordered, allow duplicates, and are indexed from 0.
ArrayListis the default, andLinkedListalso implementsDeque. Arrays.asListgives a fixed-size view of an array.List.ofandList.copyOfgive unmodifiable, null-free lists.add(i, e),get,set(which returns the old value),remove(int),indexOf/lastIndexOfandreplaceAllwork with indexes and values. Invalid indexes throwIndexOutOfBoundsException.remove(int)andremove(Object)are overloads. Anintorcharargument picks the index version.toArray(new T[0])creates a typed, independent array copy.
Practice quiz
Test yourself with the List quiz: 10 exam-style questions with explanations.
Previous: Java Collections Framework: The Collection Interface and Common Methods (OCP 21)
Next: Java Set, Queue and Deque: HashSet, TreeSet, ArrayDeque and Their Methods (OCP 21)
Related reading
- Java Collections Framework: The Collection Interface and Common Methods (OCP 21)
- Java Variable Scope and Garbage Collection (OCP 21)
- Java Legacy Collections: Hashtable, Enumeration, Properties, Stack and BitSet
- Java Collections Algorithms: Sorting, Shuffling, Binary Search and Bulk Operations
- Java Collection Copies and Views: Immutable Collections, Subranges and Unmodifiable Views

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.