Java Collections Framework
The Java Collections Framework is a unified architecture for representing and manipulating collections of objects in Java. It provides a set of interfaces (e.g., List, Set, Map) and classes (e.g., ArrayList, HashSet, HashMap) that define common data structures and algorithms for storing and processing groups of objects.
Table of Contents
Purpose of Java Collections Framework
- Unified Architecture: JCF provides a standardized way to work with collections, making it easier to write and maintain Java code.
- Reusable Data Structures: It offers reusable implementations of common data structures like lists, sets, maps, queues, etc.
- Algorithms and Utilities: JCF includes algorithms (e.g., sorting, searching) and utility methods (e.g., Collections.sort(), Collections.shuffle()) to manipulate collections efficiently.
Example in Java
Let’s illustrate the usage of Java Collections Framework with a simple example:
java
import java.util.*;
public class Main {
public static void main(String[] args) {
// Creating an ArrayList of Strings
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Iterating through the ArrayList
System.out.println("Fruits:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Creating a HashSet of Integers
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Iterating through the HashSet
System.out.println("\nNumbers:");
for (int number : numbers) {
System.out.println(number);
}
// Creating a HashMap of Integer keys and String values
Map<Integer, String> studentMap = new HashMap<>();
studentMap.put(1, "Alice");
studentMap.put(2, "Bob");
studentMap.put(3, "Carol");
// Iterating through the HashMap
System.out.println("\nStudents:");
for (Map.Entry<Integer, String> entry : studentMap.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
}
}
}
Explanation: In this example:
- ArrayList (fruits) is used to store a list of strings representing fruits.
- HashSet (numbers) is used to store a set of integers.
- HashMap (studentMap) is used to store mappings of student IDs to names.
- Iteration over collections is demonstrated using enhanced for loop for lists and sets, and entrySet() method for maps.