The Java Collections Framework is a set of interfaces and classes in the Java Standard Library that provides a unified architecture for representing and manipulating collections, such as lists, sets and maps.
It offers out-of-the-box solutions for common data structures and algorithms, allowing developers to save time, write safer code, and focus on application logic rather than reinventing the wheel.
In this series of posts on Java Collections API, we will dive deep into the List interface, Map interface and Set interface to understand how we can utilize these built-in data structures for our programming needs.
List interface
A List in Java is an ordered collection that can contain duplicate elements. The List interface extends the Collection interface and provides methods for manipulating elements based on their position in the list.
Key Features
- Ordered: The elements are stored in a specific sequence.
- Index-based: Elements can be accessed by their index in the list.
- Allows Duplicates: A list can contain duplicate elements.
- Null Elements: Most List implementations allow for storing
null
.
Core Methods
Some of the important methods declared in the List interface are:
- add(E e) // Add an element
- get(int index) // Retrieve an element by its index
- remove(int index) // Remove an element by its index
- size() // Get the size of the list
- contains(Object o) // Check if the list contains a certain object
Common Implementations
ArrayList
ArrayList
is the resizable-array implementation of the List interface. It is the go-to List implementation for many because of its general-purpose functionality.
import java.util.ArrayList;
import java.util.List;
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
String secondName = names.get(1); // Retrieves "Bob"
Pros:
- Constant-time random access
- Fast iteration
Cons:
- Slow removal and insertion at arbitrary indices
LinkedList
LinkedList
is implemented as a doubly-linked list. It is preferable for use cases that require frequent insertions and removals.
import java.util.LinkedList;
import java.util.List;
List<String> names = new LinkedList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
Pros:
- Fast insertion and removal at both ends
- Useful as a queue or stack
Cons:
- Linear time for random access
Vector
Vector
is similar to ArrayList
, but it is synchronized, making it thread-safe.
import java.util.Vector;
import java.util.List;
List<String> names = new Vector<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
Pros:
- Thread-safe
- Constant-time random access
Cons:
- Slower than ArrayList due to synchronization overhead
Conclusion
The List interface provides a powerful contract for ordered, index-based collections in Java. Depending on your specific requirements—whether it’s fast random access, frequent insertions, or thread-safety—you can choose the appropriate List implementation.