List in Java
Master the List interface in Java: ordered sequences, index-based access, key implementations, and how to choose between them for interviews.
List<E> is the most widely used interface in the Java Collections Framework. It extends Collection<E> and models an ordered sequence of elements where each element has a positional index. Lists permit duplicate elements and, in most implementations, permit null. Because ordering and index-based access are so useful, List and its implementations (ArrayList, LinkedList) appear in the vast majority of Java codebases.
What List Adds to Collection
List extends Collection with index-based operations:
| Method | Description |
|---|---|
E get(int index) |
Returns the element at the given index. |
E set(int index, E element) |
Replaces the element at index; returns the old value. |
void add(int index, E element) |
Inserts element at index, shifting subsequent elements right. |
E remove(int index) |
Removes and returns the element at index. |
int indexOf(Object o) |
Returns the index of the first occurrence of o, or -1. |
int lastIndexOf(Object o) |
Returns the index of the last occurrence of o, or -1. |
List<E> subList(int from, int to) |
Returns a view of the list from from (inclusive) to to (exclusive). |
ListIterator<E> listIterator() |
Returns a bidirectional iterator that also supports add and set. |
void sort(Comparator<? super E> c) |
Sorts the list in place (Java 8+). |
Key Properties of List
| Property | Detail |
|---|---|
| Ordering | Insertion order is always maintained |
| Duplicates | Allowed |
| Null elements | Allowed by ArrayList and LinkedList; not by List.of() |
| Index access | O(1) for ArrayList, O(n) for LinkedList |
| Thread safety | Neither ArrayList nor LinkedList is thread-safe |
Creating Lists
import java.util.ArrayList;
import java.util.List;
public class CreatingLists {
public static void main(String[] args) {
// Mutable list — use when you need to add/remove
List<String> mutable = new ArrayList<>(List.of("A", "B", "C"));
mutable.add("D");
mutable.remove("B");
System.out.println(mutable); // [A, C, D]
// Immutable list (Java 9+) — throws UnsupportedOperationException on mutation
List<String> immutable = List.of("X", "Y", "Z");
System.out.println(immutable); // [X, Y, Z]
// List.copyOf — immutable deep copy of another collection (Java 10+)
List<String> copy = List.copyOf(mutable);
System.out.println(copy); // [A, C, D]
}
}
Example: Index-Based Operations
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ListOperations {
public static void main(String[] args) {
List<Integer> scores = new ArrayList<>(List.of(70, 85, 90, 60, 75));
// Index-based get and set
System.out.println("Third score: " + scores.get(2)); // 90
scores.set(3, 65);
System.out.println("Updated: " + scores); // [70, 85, 90, 65, 75]
// Insert at specific position
scores.add(0, 100);
System.out.println("After insert: " + scores); // [100, 70, 85, 90, 65, 75]
// Sort in place
scores.sort(null); // natural order
System.out.println("Sorted: " + scores); // [65, 70, 75, 85, 90, 100]
// subList view (backed by original — changes reflect both ways)
List<Integer> top3 = scores.subList(3, 6);
System.out.println("Top 3: " + top3); // [85, 90, 100]
// Binary search (list must be sorted)
int idx = Collections.binarySearch(scores, 75);
System.out.println("Index of 75: " + idx); // 2
}
}
List Implementations Compared
| Feature | ArrayList |
LinkedList |
|---|---|---|
| Internal structure | Resizable array | Doubly-linked list |
get(i) |
O(1) | O(n) |
add at end |
Amortized O(1) | O(1) |
add/remove at index |
O(n) | O(n) to find, O(1) to link |
| Memory overhead | Low | High (two pointers per node) |
| Cache locality | Good | Poor |
| Also implements | List, RandomAccess |
List, Deque, Queue |
| Best use case | Random access, iteration | Frequent add/remove at both ends |
In practice, ArrayList is the right choice for the vast majority of use cases. LinkedList is only preferable when you frequently add/remove at both ends and never need random access.
Common Mistakes
- Removing an element by index vs. by value.
list.remove(2)removes the element at index 2.list.remove(Integer.valueOf(2))removes the first occurrence of the value2. This distinction is a common source of bugs when working withList<Integer>. - Structural modification during iteration. Calling
list.remove(element)inside a for-each loop throwsConcurrentModificationException. Uselist.removeIf(predicate)or an explicitIterator. - Using
Arrays.asListand assuming a fully mutable list.Arrays.asList(arr)returns a fixed-sizeListbacked by the array. You can callset()but notadd()orremove()— those throwUnsupportedOperationException. - Using
List.ofand trying to addnull.List.of(...)creates an immutable list that throwsNullPointerExceptionif you passnullas an element, andUnsupportedOperationExceptionon any mutation. - Assuming
subListis independent. The list returned bysubList(from, to)is a view backed by the original list. Mutating the sublist mutates the original, and structurally modifying the original after creating the sublist makes the sublist invalid.
Best Practices
- Declare variables as
List<E>, notArrayList<E>, so you can swap implementations freely. - Use
ArrayListby default; only switch toLinkedListif profiling proves a benefit. - Prefer
List.of(...)(Java 9+) for small, fixed collections — it is more concise and enforces immutability. - Use
list.sort(Comparator)orCollections.sort(list)rather than manual bubble-sort implementations. - When removing multiple elements by condition, use
list.removeIf(predicate)— it is O(n) and avoidsConcurrentModificationException.
Interview Questions
1. What is the List interface in Java?
List<E> is an ordered collection that allows duplicates and provides positional (index-based) access. It extends Collection<E> and is implemented by ArrayList, LinkedList, and Vector (legacy). The key guarantee is that elements maintain the order in which they were inserted.
2. What is the difference between ArrayList and LinkedList?
ArrayList is backed by a resizable array; get(i) is O(1) but add/remove in the middle is O(n) due to shifting. LinkedList is backed by a doubly-linked list; get(i) is O(n) but add/remove at either end is O(1). For most use cases ArrayList is faster in practice because of better cache locality.
3. What does Arrays.asList return, and what are its limitations?
Arrays.asList(T... a) returns a fixed-size List backed by the given array. You can get and set elements, but calling add or remove throws UnsupportedOperationException. To get a fully mutable copy, wrap it: new ArrayList<>(Arrays.asList(arr)).
4. What is the difference between List.of and new ArrayList?
List.of(...) (Java 9+) returns an immutable list: it does not allow mutation, does not allow null elements, and has no guaranteed internal implementation. new ArrayList<>(...) returns a mutable list backed by a resizable array, allows null, and supports all List operations.
5. How does list.remove(int index) differ from list.remove(Object o) for List<Integer>?
For a List<Integer>, list.remove(2) resolves to the remove(int index) overload and removes the element at position 2. To remove the value 2 from the list, you must use list.remove(Integer.valueOf(2)) to force the remove(Object o) overload. This autoboxing ambiguity is a classic interview trap.
6. Is List thread-safe?
No. ArrayList and LinkedList are not synchronised. For thread-safe use, you can wrap them with Collections.synchronizedList(list) (coarse-grained locking) or use CopyOnWriteArrayList (from java.util.concurrent) which is optimised for read-heavy scenarios.
7. What is a ListIterator and when would you use it?
ListIterator<E> extends Iterator<E> with bidirectional traversal (hasPrevious(), previous()), and mutation methods (add(e), set(e)) that work safely during iteration. Use it when you need to iterate backwards, replace elements in place, or insert elements while traversing — all of which are not possible with a plain Iterator.
Summary
List<E>extendsCollection<E>with positional (index-based) access, insertion-order guarantees, and duplicate support.ArrayListis the default choice: O(1) random access, amortized O(1) append.LinkedListis preferable only for frequent add/remove at both ends with no random access.List.of(...)creates immutable lists that reject nulls;Arrays.asList(...)creates fixed-size views that allowsetbut notadd/remove.- For safe removal during iteration, use
removeIfor an explicitIterator.
Continue Learning
Previous: Collection | Next: ArrayList
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.