List
About
The List interface in Java is a part of the java.util package and provides an ordered collection (sequence) of elements. It is a parent interface implemented by classes like ArrayList, LinkedList, and Vector.
Interface:
Listis an interface, meaning it cannot be instantiated directly. It defines methods that must be implemented by its concrete classes.Order: Elements in a
Listmaintain their insertion order.Allows Duplicates: A
Listcan contain duplicate elements.Generics Support:
Listcan be declared with generics to enforce type safety at compile time.Index-Based Access: Provides access to elements using zero-based indexing.
Features
Ordered Collection: Retains the order of insertion.
Index-Based Access: Retrieve, add, or remove elements by index.
Allows Null: Accepts
nullas an element (implementation-dependent).Generics: Allows type-safe collections:
List<String> names = new ArrayList<>();Polymorphism: Use
Listas the reference type for flexibility:
List<Integer> numbers = new LinkedList<>();Iterators: Supports iterators for traversal.
Thread Safety: Use synchronized versions like
Collections.synchronizedList()for thread-safe operations.Stream API Compatibility: Efficient bulk operations like filtering and mapping.
Immutable List: Use
List.of()to create immutable lists.
Key Methods
add(E e): Adds an element.get(int index): Retrieves an element by index.set(int index, E element): Replaces the element at a specified position.remove(int index)/remove(Object o): Removes an element.size(): Returns the number of elements.isEmpty(): Checks if the list is empty.contains(Object o): Checks if the list contains a specified element.clear(): Removes all elements.addAll(Collection<? extends E> c): Adds all elements of a collection.retainAll(Collection<?> c): Retains only elements present in the specified collection.subList(int fromIndex, int toIndex): Returns a portion of the list.toArray(): Converts the list into an array.
List Implementations
List Implementations1. ArrayList
Description: A resizable array-backed implementation of
List.Key Features:
Allows fast random access to elements (
O(1)access by index).Slower when frequently inserting or deleting elements in the middle (
O(n)for add/remove).Not synchronized (not thread-safe).
Use Case: When frequent random access is required and insertions/deletions are infrequent.
Class:
java.util.ArrayList
2. LinkedList
Description: A doubly-linked list implementation of
List.Key Features:
Efficient for frequent insertions and deletions (
O(1)for add/remove at ends).Slower for random access as it requires traversal (
O(n)access by index).Implements both
ListandDeque(can be used as a queue or stack).
Use Case: When frequent insertions and deletions are required in the middle of the list.
Class:
java.util.LinkedList
3. Vector
Description: A synchronized, thread-safe version of
ArrayList.Key Features:
Automatically grows and shrinks in size as elements are added or removed.
Synchronized for thread-safe operations, but slower due to overhead.
Legacy class, replaced by
ArrayListfor non-thread-safe use cases andCopyOnWriteArrayListfor thread-safe use cases.
Use Case: When thread-safe operations are needed and alternative solutions are unavailable.
Class:
java.util.Vector
4. Stack
Description: A last-in-first-out (LIFO) stack implementation based on
Vector.Key Features:
Extends
Vectorand adds stack-specific methods likepush,pop, andpeek.Inherits synchronization from
Vector.Considered a legacy class; use
Dequeimplementations likeArrayDequeinstead.
Use Case: For LIFO (stack) behavior in older Java versions.
Class:
java.util.Stack
5. CopyOnWriteArrayList (Thread-Safe Implementation)
Description: A thread-safe version of
ArrayListwhere all write operations (add/remove) create a new copy of the array.Key Features:
Iterators do not throw
ConcurrentModificationException.High overhead for write operations but efficient for read-heavy scenarios.
Use Case: When multiple threads mostly read data and modifications are infrequent.
Class:
java.util.concurrent.CopyOnWriteArrayList
CopyOnWriteArrayList is excellent for concurrent reads but is inefficient for frequent writes due to its internal array copy behavior.
Suggestion: Use Collections.synchronizedList(new ArrayList<>()) instead, if we are writing more than reading.
6. SynchronizedList (Thread-Safe Implementation)
Description: A thread-safe wrapper around any
List, created usingCollections.synchronizedList().Key Features:
Provides synchronized access to all
Listoperations.External synchronization is required for iteration to avoid
ConcurrentModificationException.
Use Case: When an existing
Listneeds to be made thread-safe.Class:
java.util.Collections.
6. Immutable List (Immutable Implementations)
Description: Provides an unmodifiable, immutable list implementation.
Key Features:
Created using
List.of(...)orCollections.unmodifiableList(...).Any attempt to modify the list will throw
UnsupportedOperationException.
Use Case: When we want a list that cannot be modified.
Class:
java.util.List(created using factory methods likeList.of()orCollections.unmodifiableList())
Custom Implementations of List
List1. AbstractList
Description: A skeletal implementation of the
Listinterface for creating customListimplementations.Key Features:
Reduces the effort required to implement a custom
List.Requires only the implementation of
getandsize.
Use Case: When creating a custom
Listimplementation.Class:
java.util.AbstractList.
2. AbstractSequentialList
Description: A skeletal implementation of the
Listinterface for sequential access lists.Key Features:
Designed for data structures where elements are accessed sequentially (e.g., linked lists).
Requires implementing
listIteratorandsize.
Use Case: When creating a sequential access list.
Class:
java.util.AbstractSequentialList.
Last updated