List Interface in Java
The List interface in Java extends Collection and represents an ordered sequence of elements. Unlike a raw Collection, a List guarantees insertion order an...
Defining the List Interface
The List interface in Java extends Collection and represents an ordered sequence of elements. Unlike a raw Collection, a List guarantees insertion order and allows positional access through a zero-based index. Elements can be duplicated, meaning the same object or value may appear at multiple positions in the list.
Key methods defined by List include get(int index) to retrieve an element at a position, set(int index, E element) to replace an element, add(int index, E element) to insert at a specific position, and remove(int index) to delete by position. These position-based operations are what separate List from the broader Collection interface.
List also introduces ListIterator, which extends the standard Iterator and allows bidirectional traversal as well as in-place modification during iteration.
Iteration and Sublist Operations
Java provides multiple ways to iterate a List. The classic for loop using an index works well when the position matters. The enhanced for-each loop is cleaner for sequential access. The iterator() and listIterator() methods give explicit control, especially useful when removing elements mid-traversal without a ConcurrentModificationException.
The subList(int fromIndex, int toIndex) method returns a view of a portion of the list. Modifications to the sublist are reflected in the original, so clearing a sublist is an efficient way to delete a range of elements: list.subList(2, 5).clear(); removes elements at indices 2, 3, and 4 from the original list in one call.
Searching is supported by indexOf(Object o), which returns the first occurrence, and lastIndexOf(Object o) for the last. Both run in O(n) time for most implementations.
Practical Tip and Common Pitfall
One interview question about List asks whether it allows null values. Yes, List implementations like ArrayList and LinkedList permit null elements, and you can even have multiple nulls at different positions. However, some thread-safe alternatives like CopyOnWriteArrayList also allow nulls while others like ConcurrentLinkedDeque do not.
A short example: List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "cherry")); fruits.add(1, "avocado"); System.out.println(fruits.get(1)); prints avocado because insertion at index 1 shifts subsequent elements right.
A common pitfall is calling remove(int index) versus remove(Object o) on a List<Integer>. When you write list.remove(2), Java calls the index-based version and removes the element at position 2. To remove the integer value 2 as an object, you must write list.remove(Integer.valueOf(2)). This distinction trips up many developers in both code and interviews.