Java Tutorial

Collections Framework

List, Set, Map, ArrayList, HashSet, and HashMap

What is the Collections Framework?

In Java, if you want to store a group of objects (like a list of users or a dictionary of scores), you use the Java Collections Framework (JCF). It provides a set of pre-built classes and interfaces that are highly optimized for common data storage tasks.
It lives in the java.util package.
java
import java.util.*;

// Interface 'List' = The "what"
// Class 'ArrayList' = The "how"
List<String> names = new ArrayList<>();
names.add("Alpha");
names.add("Beta");

Comparisons: The Three Essential Interfaces

Wait! Before you use a collection, you must pick the right Interface based on how you want to store your data:
InterfaceBehaviorImplementation Class
ListOrdered; allows duplicates.ArrayList, LinkedList
SetUnordered; UNIQUE items only.HashSet, TreeSet
MapKey-Value Pairs.HashMap, TreeMap

1. List (Standard Workhorse)

An ArrayList is a dynamic array that grows automatically. Because its items are stored next to each other in memory, it's the fastest option for 90% of your tasks.
java
List<Integer> nums = new ArrayList<>();
nums.add(10);
nums.get(0); // Quick access!

2. Set (Uniqueness Matters)

A HashSet is unordered, but it's very fast at checking if an item already exists. It uses the object's hashCode() to find data almost instantly.
java
Set<String> uniqueColors = new HashSet<>();
uniqueColors.add("Red");
uniqueColors.add("Red"); // Ignored! (Only one "Red" allowed!)

3. Map (Key-Value Dictionary)

A HashMap associates a key with a value. Like a real dictionary: the word is the "key," and the definition is the "value."
java
Map<String, Integer> scores = new HashMap<>();
scores.put("Alpha", 100);
scores.put("Beta", 50);

System.out.println(scores.get("Alpha")); // Prints 100!

Summary

FeatureMethod / SyntaxPurpose
Add.add(v) or .put(k, v)Put an item in
Search.contains(v) or .containsKey(k)Check if x exists
Size.size()Number of items
OrderArrayList (Ordered) vs HashSet (Random)Logic of organization
Empty.isEmpty()Faster than checking size!
Clear.clear()Wipe the collection
Best ForLists, unique sets, dictionaries, generic storage
InterfacePick the "List" or "Map" first!
ClassPick the "ArrayList" or "HashMap" second!
IteratorStandard way to step through any collection
StreamModern high-speed processing (Java 8+)
GenericsList<String> ensures type safety!
WrapperYou MUST use Integer instead of int!
NullMost collections allow at least one null value
CollectionsUse Collections.sort(list) (The helper class!)
ModernList.of("A", "B") (Unmutable small lists! - Java 9+)
PerformanceArrayList = O(1) access; HashMap = O(1) search
ThreadStandard collections are NOT safe for multi-threading!
SynchronizedUse Collections.synchronizedList(l) for thread safety
ConcurrentSpecial high-speed thread-safe collections in java.util.concurrent
AlgorithmSearch, sort, reverse logic is pre-built!
FrameworkReplacing the older, slower Vector and Hashtable
MemoryJVM manages all memory; no manual free()!
IdentitySet equality depends on equals() and hashCode()!
SafeImpossible to "go past the end" like in C arrays!
TreeTreeMap keeps keys in alphabetical/natural order!