Java List Interface
Working with ordered collections that allow duplicates
📋 What is a Java List?
List is an ordered collection interface that allows duplicate elements and provides indexed access to elements, making it perfect for sequential data storage.
// Creating and using a List
import java.util.*;
List<String> students = new ArrayList<>();
students.add("Alice");
students.add("Bob");
students.add("Alice"); // Duplicates allowed
System.out.println(students.get(0)); // Access by index
Output:
Alice
List Key Features
Indexed Access
Access elements by position
list.get(0); // First element
Allows Duplicates
Same element can appear multiple times
list.add("Apple");
list.add("Apple"); // OK
Maintains Order
Elements stay in insertion order
list.add("First");
list.add("Second"); // Order preserved
Dynamic Size
Grows and shrinks automatically
list.size(); // Current size
🔹 Common List Operations
Essential methods you'll use with List interface:
import java.util.*;
public class ListOperations {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
// Adding elements
numbers.add(10); // Add at end
numbers.add(20);
numbers.add(1, 15); // Add at specific index
// Accessing elements
System.out.println("First: " + numbers.get(0));
System.out.println("Size: " + numbers.size());
// Modifying elements
numbers.set(0, 5); // Replace element at index 0
// Searching
int index = numbers.indexOf(20);
System.out.println("Index of 20: " + index);
// Removing elements
numbers.remove(1); // Remove by index
numbers.remove(Integer.valueOf(20)); // Remove by value
System.out.println("Final list: " + numbers);
}
}
Output:
First: 10
Size: 3
Index of 20: 2
Final list: [5]
🔹 List Implementations
Different ways to implement the List interface:
🔸 ArrayList vs LinkedList vs Vector
- ArrayList: Best for frequent reading, slower for insertions in middle
- LinkedList: Best for frequent insertions/deletions, slower for random access
- Vector: Like ArrayList but synchronized (thread-safe), generally avoided
// Different List implementations
List<String> arrayList = new ArrayList<>(); // Most common
List<String> linkedList = new LinkedList<>(); // For frequent modifications
List<String> vector = new Vector<>(); // Thread-safe (rarely used)
// All implement List interface, so methods are the same
arrayList.add("Hello");
linkedList.add("Hello");
vector.add("Hello");
🔹 Iterating Through Lists
Different ways to loop through List elements:
List<String> fruits = Arrays.asList("Apple", "Banana", "Orange");
// 1. Enhanced for loop (recommended)
for (String fruit : fruits) {
System.out.println(fruit);
}
// 2. Traditional for loop with index
for (int i = 0; i < fruits.size(); i++) {
System.out.println(i + ": " + fruits.get(i));
}
// 3. Iterator
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// 4. Stream API (Java 8+)
fruits.stream().forEach(System.out::println);
Output (for each method):
Apple
Banana
Orange