The Java Collections Framework (JCF) is a unified architecture that provides data structures and algorithms for storing and manipulating groups of objects. It is an essential part of the Java programming language, enabling developers to work with collections of data in a consistent manner.
A collection in Java is a group of objects, known as elements. Collections allow for various operations such as adding, removing, and accessing elements. Java Collections are part of the java.util
package.
The Java Collections Framework comprises several core interfaces that define the contract for collection classes. Below are the most important interfaces:
The root of the collection hierarchy. It defines basic operations for all collections. Common methods include:
add(E e)
: Adds an element to the collection.remove(Object o)
: Removes an element.size()
: Returns the number of elements.clear()
: Removes all elements.A specialized interface for ordered collections that can contain duplicate elements. Common implementations include ArrayList
and LinkedList
.
import java.util.*;
public class ListExample {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
list.add("Banana"); // Duplicates allowed
System.out.println("List: " + list);
}
}
A collection that cannot contain duplicate elements. Implementations include HashSet
, LinkedHashSet
, and TreeSet
.
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Banana"); // Duplicate will be ignored
System.out.println("Set: " + set);
}
}
A collection of key-value pairs, where each key is unique. Common implementations are HashMap
, LinkedHashMap
, and TreeMap
.
import java.util.*;
public class MapExample {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
System.out.println("Map: " + map);
}
}
Now that we have an understanding of the core interfaces, let’s delve deeper into the major implementations of collections in Java.
ArrayList
is a resizable array implementation of the List
interface. It allows for dynamic resizing and provides fast random access to elements.
Key Features:
Example:
import java.util.*;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Accessing elements
System.out.println("First fruit: " + fruits.get(0));
// Iterating over ArrayList
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
LinkedList
is a doubly-linked list implementation of the List
interface. It provides better performance for insertions and deletions compared to ArrayList
.
Key Features:
Example:
import java.util.*;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList fruits = new LinkedList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
// Adding at the beginning
fruits.addFirst("Orange");
// Iterating over LinkedList
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
HashSet
is an implementation of the Set
interface backed by a hash table. It does not allow duplicate elements and does not guarantee any order of iteration.
Key Features:
Example:
import java.util.*;
public class HashSetExample {
public static void main(String[] args) {
Set set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Banana"); // Duplicate ignored
// Iterating over HashSet
for (String fruit : set) {
System.out.println(fruit);
}
}
}
TreeSet
is a sorted set implementation that uses a red-black tree structure. It maintains elements in their natural order or according to a specified comparator.
Key Features:
HashSet
for basic operationsExample
import java.util.*;
public class TreeSetExample {
public static void main(String[] args) {
Set set = new TreeSet<>();
set.add("Banana");
set.add("Apple");
set.add("Cherry");
// Iterating over TreeSet
for (String fruit : set) {
System.out.println(fruit); // Outputs in sorted order
}
}
}
HashMap
is an implementation of the Map
interface that uses a hash table. It allows for null values and one null key.
Key Features:
Example:
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
// Accessing elements
System.out.println("Value for Banana: " + map.get("Banana"));
// Iterating over HashMap
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
TreeMap
is a red-black tree-based implementation of the Map
interface that maintains order among its keys.
Key Features:
HashMap
for basic operationsExample:
import java.util.*;
public class TreeMapExample {
public static void main(String[] args) {
Map map = new TreeMap<>();
map.put("Banana", 2);
map.put("Apple", 1);
map.put("Cherry", 3);
// Iterating over TreeMap
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Java Collections Framework provides several utility methods to perform common operations on collections, such as sorting, searching, and shuffling.
The Collections
class provides static methods for sorting collections.
import java.util.*;
public class SortingExample {
public static void main(String[] args) {
List list = Arrays.asList("Banana", "Apple", "Cherry");
Collections.sort(list);
System.out.println("Sorted List: " + list);
}
}
You can use the Collections.binarySearch()
method to perform a binary search on a sorted list.
import java.util.*;
public class SearchingExample {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry"));
Collections.sort(list);
int index = Collections.binarySearch(list, "Banana");
System.out.println("Index of Banana: " + index);
}
}
The Collections.shuffle()
method randomly shuffles the elements in a collection.
import java.util.*;
public class ShufflingExample {
public static void main(String[] args) {
List list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry"));
Collections.shuffle(list);
System.out.println("Shuffled List: " + list);
}
}
An iterator is an object that enables you to traverse through a collection, accessing its elements one at a time. The Iterator
interface provides methods for this purpose.
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Using Iterator
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Java also provides an enhanced for loop (also known as the “for-each” loop) for iterating over collections.
import java.util.*;
public class EnhancedForLoopExample {
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Enhanced for loop
for (String fruit : list) {
System.out.println(fruit);
}
}
}