The Collections Framework is a set of pre-built classes that act like "Smart Arrays." You don't have to worry about how big they are; they grow and shrink automatically as you add or remove items.
While there are many types, these are the "Big Three" you must know:
ArrayList: Like an array, but can change size. Best for general lists.HashSet: A collection that does not allow duplicates. Perfect for storing unique IDs.HashMap: A "Dictionary." It stores data in Key-Value pairs (e.g., "Username" -> "John123").
Key Features
Dynamic Resizing: No more
ArrayIndexOutOfBoundsExceptionwhen adding items.Built-in Methods: Easily sort, search, and clear your data.
Generics
<T>: You tell the collection what type of objects it holds (e.g.,ArrayList<String>).
The Code Example:
import java.util.*; // Import the collection tools
public class CollectionsDemo {
public static void main(String[] args) {
// 1. ArrayList (The Dynamic List)
List<String> students = new ArrayList<>();
students.add("Alice");
students.add("Bob");
students.add("Charlie");
students.remove("Bob"); // Easily remove by value
System.out.println("Student List (Size: " + students.size() + "): " + students);
// 2. HashSet (The Unique Set)
Set<Integer> uniqueIDs = new HashSet<>();
uniqueIDs.add(101);
uniqueIDs.add(102);
uniqueIDs.add(101); // This duplicate will be ignored!
System.out.println("Unique IDs: " + uniqueIDs);
// 3. HashMap (The Dictionary/Key-Value Map)
// Store: Country Name (Key) -> Capital City (Value)
Map<String, String> capitals = new HashMap<>();
capitals.put("USA", "Washington D.C.");
capitals.put("India", "New Delhi");
capitals.put("France", "Paris");
System.out.println("Capital of India: " + capitals.get("India"));
// Printing all keys in the map
System.out.println("Countries tracked: " + capitals.keySet());
}
}Expected Output:
Student List (Size: 2): [Alice, Charlie]
Unique IDs: [101, 102]
Capital of India: New Delhi
Countries tracked: [USA, France, India]Collections are the backbone of modern Java apps.
ArrayListis used for almost every list of data you see in an app.HashMapis used for caching, configuration, and connecting related data (like a user's ID to their Profile object). Learning these makes you a much faster coder because you don't have to write your own logic for managing data structures.
Pro Tip: Always use the Interface name on the left side (like
List<String> list = new ArrayList<>();). This makes your code more flexible if you decide to change to aLinkedListlater!