In Java, a List is an ordered collection (also called a sequence) that allows duplicate elements. It is part of the Java Collections Framework and is defined in the java.util
package.
🔑 Key Points about Lists
- They maintain insertion order.
- Can contain duplicate elements.
- Elements can be accessed via index (zero-based).
- Lists are dynamic in size (unlike arrays).
✅ Common Implementations of List
- ArrayList
- Backed by a dynamic array.Fast for random access.Slower for inserting/removing elements in the middle.
- LinkedList
- Implemented as a doubly linked list.Better for frequent insertions/deletions.Slower for random access.
- Vector (Legacy)
- Similar to
ArrayList
but synchronized (thread-safe). - Rarely used nowadays (use
Collections.synchronizedList()
instead).
- Similar to
🔧 Useful List Methods
List<String> list = new ArrayList<>();
list.add("A"); // Add element
list.add("B");
list.add("C");
list.get(1); // Access element at index → "B"
list.set(1, "BB"); // Replace element at index 1
list.remove(0); // Remove element at index 0
list.size(); // Get number of elements
list.contains("C"); // Check if element exists
list.isEmpty(); // Check if list is empty
for (String s : list) { // Iteration
System.out.println(s);
}