List
A List in Java is an ordered collection that allows storing multiple elements, including duplicates. It is part of the Java Collections Framework and provides index-based access, meaning each element in the list has a specific position (starting from index 0).
Types of Lists in JavaThe List has three main implementations:
1. ArrayList (Fast for Searching, Slow for Inset/Delete in Middle)
An ArrayList is a resizable array implementation of the List. It is best when fast searching and random acess are required.
Advantage
- Automatically resizes when adding/removing elements.
Disadvantages
- Slow inset/delete operations in the middle
Example:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names); // Output: [Alice, Bob, Charlie]
}
}
2. LinkedList (Fast Inset/Delete, Slow Serching)
A LinkedList stores elements as nodes where each node contains a reference to the next and previous node. This makes insertion adn deletion faster compared to ArrayList.
Advantage
- Fast insetion/deletions
Disadvantages
- Slow searching
Example:
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.addFirst(5); // Add element at the beginning
System.out.println(numbers); // Output: [5, 10, 20]
}
}
3. Vector (Thread-Safe, But Slower Than ArrayList)
A Vector is similar to an ArrayList but sunchronized, meaning it is thread-safe and can be used in multi-threaded environments.
Advantage
- Thread-safe
Disadvantages
- Slower than ArrayList
Example:
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector cities = new Vector<>();
cities.add("New York");
cities.add("London");
System.out.println(cities); // Output: [New York, London]
}
}
ArrayList Vs. LinkedList Vs. Vector
Feature | ArrayList | LinkedList | Vector |
---|---|---|---|
Storage Type | Resizable Array | Doubly Linked List | Resizable Array |
Allows Duplicates ? | Yes | Yes | Yes |
Index-Based Access ? | Fast | Slow | Fast |
Insertion/Deletion Speed | Slow | Fast | Slow |
Thread Safety | No | No | Yes |