Lesson 37: Working with the List Interface
The List interface is the most commonly used collection. It guarantees ordered access and allows duplicates.
1. ArrayList
- Implementation: Internally uses a dynamic array.
- Performance: Excellent for random access (getting elements by index) but slower for insertions/deletions in the middle.
java import java.util.ArrayList; import java.util.List;
// List is the reference type, ArrayList is the implementation type (Polymorphism)
List
names.add("Bob"); names.add("Alice"); names.add("Bob"); // Duplicates allowed
System.out.println(names.get(1)); // Alice (Fast access) names.remove(0); // Removes Bob at index 0 (Potentially slow shift)
2. LinkedList
- Implementation: Internally uses a doubly linked list structure.
- Performance: Slower for random access (must traverse links) but extremely efficient for insertions/deletions at the start or middle.
java import java.util.LinkedList;
LinkedList
3. The Diamond Operator (<>)
In modern Java (JDK 7+), you can use the diamond operator (<>) instead of repeating the type argument on the right-hand side, improving readability.
java
List