Collections
In Java, the Collections Framework is a unified architecture for representing and manipulating collections of objects. It provides a set of interfaces, implementations, and algorithms to handle various types of data collections like lists, sets, and maps. The java.util
package contains all the collection classes and interfaces.
Core Interfaces of Collections Framework
Collection Interface:
- The root interface of the collection hierarchy. It defines common operations like
add()
,remove()
,size()
, andclear()
, which are implemented by all other collection classes.
- The root interface of the collection hierarchy. It defines common operations like
Set Interface:
- Represents a collection of unique elements (no duplicates). Common implementations include
HashSet
,TreeSet
, andLinkedHashSet
.
- Represents a collection of unique elements (no duplicates). Common implementations include
List Interface:
- Represents an ordered collection that allows duplicate elements. Common implementations include
ArrayList
,LinkedList
, andVector
.
- Represents an ordered collection that allows duplicate elements. Common implementations include
Map Interface:
- Represents a collection of key-value pairs, where each key is unique. Common implementations include
HashMap
,TreeMap
, andLinkedHashMap
.
- Represents a collection of key-value pairs, where each key is unique. Common implementations include
SortedSet and SortedMap:
- Specialized versions of
Set
andMap
that maintain their elements in a sorted order.TreeSet
implementsSortedSet
andTreeMap
implementsSortedMap
.
- Specialized versions of
Benefits of Using Collections Framework
Efficiency:
- Provides efficient and optimized algorithms for storing and manipulating collections.
Reusability:
- The framework allows you to reuse implementations for common data structures such as lists, sets, and maps.
Flexibility:
- The framework provides a variety of collections, each tailored to specific use cases (e.g.,
HashSet
for fast lookups,ArrayList
for dynamic arrays).
- The framework provides a variety of collections, each tailored to specific use cases (e.g.,
Interoperability:
- The various implementations of the core interfaces are interchangeable, allowing you to switch between them with minimal changes to your code.
Example: Using Collections to Store Data
import java.util.*;
public class CollectionsExample {
public static void main(String[] args) {
// Using a List to store elements
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// Using an Iterator to iterate over the collection
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}