Collections Framework

Arrays are useful, but they have one big limitation: their size is fixed the moment you create them. The Collections Framework gives Java a set of ready-made data structures — lists, sets, and maps — that can grow and shrink dynamically as your program runs, along with a consistent set of methods to work with them.

Core Interfaces and Implementations

Interface / ClassOrdered?Duplicates?Stores
List / ArrayListYes (insertion order)AllowedA sequence of elements
Set / HashSetNoNot allowedA collection of unique elements
Map / HashMapNoUnique keys, duplicate values allowedKey-value pairs

List, Set, and Map are interfaces — they describe what the collection can do. ArrayList, HashSet, and HashMap are concrete classes that actually implement that behavior, and are the ones you'll reach for most often.

ArrayList — An Ordered, Resizable List

An ArrayList works like an array that automatically grows as you add elements. Common operations are add, get, remove, and size:

List<String> names = new ArrayList<>();
names.add("Aman");
names.add("Priya");
names.add("Rohit");

System.out.println(names.get(0));    // Aman
names.remove("Priya");
System.out.println(names.size());  // 2

for (String name : names) {
  System.out.println(name); // for-each loop over the list
}
Note: The <String> in List<String> is a generic type parameter — it tells the compiler this list only holds String objects. We'll cover generics properly on the next page.

HashMap — Key-Value Pairs

A HashMap stores data as key-value pairs, so you can look up a value quickly using its key. Common operations are put, get, and containsKey:

Map<String, Integer> ages = new HashMap<>();
ages.put("Aman", 25);
ages.put("Priya", 30);

System.out.println(ages.get("Aman"));          // 25
System.out.println(ages.containsKey("Rohit")); // false

for (Map.Entry<String, Integer> entry : ages.entrySet()) {
  System.out.println(entry.getKey() + " is " + entry.getValue());
}

entrySet() returns every key-value pair in the map, which is the standard way to loop over a HashMap when you need both the key and the value.

HashSet — Unique, Unordered Elements

A HashSet automatically rejects duplicates — useful whenever you only care that something exists, not how many times it was added:

Set<String> colors = new HashSet<>();
colors.add("Red");
colors.add("Red"); // ignored, "Red" is already present
System.out.println(colors.size()); // 1

Quick recap:

  • Collections grow and shrink dynamically, unlike fixed-size arrays.
  • List/ArrayList — ordered, allows duplicates.
  • Set/HashSet — no duplicates, no guaranteed order.
  • Map/HashMap — key-value pairs, keys are unique.
  • Collections are built on generics (the <Type> syntax), which keep them type-safe.
Next steps: Head to Generics for a full look at the <Type> syntax that powers type-safe collections.