The Java Collections Framework provides a set of interfaces and classes for working with groups of objects. It includes lists, sets, and maps, which are commonly used to store and manipulate data.
import java.util.ArrayList;
import java.util.List;
public class CollectionsExample {
public static void main(String[] args) {
List names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println("Names List: " + names);
}
}
The List interface is used to store ordered collections. The ArrayList class is one of the implementations of the List interface, which allows dynamic resizing.
import java.util.HashSet;
import java.util.Set;
public class CollectionsExample {
public static void main(String[] args) {
Set uniqueNames = new HashSet<>();
uniqueNames.add("Alice");
uniqueNames.add("Bob");
uniqueNames.add("Alice"); // Duplicate value
System.out.println("Unique Names Set: " + uniqueNames);
}
}
The Set interface is used to store unique elements. The HashSet class is one of the implementations, and it automatically removes duplicates from the collection.
import java.util.HashMap;
import java.util.Map;
public class CollectionsExample {
public static void main(String[] args) {
Map phoneBook = new HashMap<>();
phoneBook.put("Alice", 12345);
phoneBook.put("Bob", 67890);
System.out.println("Phone Book: " + phoneBook);
}
}
The Map interface stores key-value pairs. In this example, a HashMap is used to associate names with phone numbers.