Arrays are useful but rigid, since their size is fixed the moment they are created. Java's collections framework solves this with flexible structures that grow and shrink as items are added or removed, and the two used most often are the list and the map.
The list
A list keeps its items in a specific order and grows automatically as needed. ArrayList is the most common implementation:
List<String> names = new ArrayList<>();
names.add("Ann");
names.add("Bob");
String first = names.get(0);
names.remove("Bob");Looping through a list
for (String name : names) {
System.out.println(name);
}The set
A set is similar to a list but never allows duplicate values, which makes it the natural choice whenever uniqueness matters more than order, such as tracking which usernames have already been seen:
Set<String> seen = new HashSet<>();
seen.add("ann");
boolean isDuplicate = !seen.add("ann"); // true, already presentThe map
A map stores pairs of a key and a value, and values are looked up by their key rather than by position, much like a dictionary:
Map<String, Integer> ages = new HashMap<>();
ages.put("Ann", 30);
int annAge = ages.get("Ann");
boolean hasBob = ages.containsKey("Bob");Looping through a map
Iterating a map usually means visiting each key and value pair together, using entrySet:
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + " is " + entry.getValue());
}Choosing an implementation
- ArrayList suits most list needs, offering fast access by position.
- LinkedList is rarely needed but can help when items are frequently inserted or removed from the middle of a very large list.
- HashMap offers fast lookups but does not guarantee any particular order.
- TreeMap keeps its keys sorted automatically, at a small performance cost compared to HashMap.
A note on autoboxing
Collections can only hold objects, not primitive values directly, which is why Map<String, Integer> uses the object type Integer rather than the primitive int. Java converts between the two automatically, a process called autoboxing, but it is worth knowing that a collection of Integer objects carries slightly more memory overhead than a plain array of int values.
When to use which
Reach for a list when order matters and duplicates are allowed, a set when only uniqueness matters, and a map whenever values need to be looked up by a meaningful key rather than a position, which together cover the overwhelming majority of everyday data-handling needs in Java.