Java Fundamentals, Part 3: Collections and Generics You'll Actually Use
Java & Spring Boot for Beginners · Part 5 of 14
- #Java
- #Spring Boot
- #Beginners
- #Fundamentals
Part 4 ended with GroupBooking
holding its tickets in a plain array: Ticket[] tickets, filled once through
a varargs constructor and never touched again. That's fine for a demo. It
falls apart the moment a booking needs to grow — someone adds a friend at the
last minute, someone else cancels — because an array's size is fixed the
instant you create it. Growing one means allocating a new, bigger array and
copying everything over. Nobody wants to write that by hand for every method
that needs a variable-length group of things, so nobody does. You reach for a
collection instead.
Java's collections library is bigger than you need on day one. In ten years of writing this stuff I reach for four types constantly and everything else rarely enough that I look up the API each time. This post covers those four, plus the one language feature that makes all of them safe to use: generics.
List: an ordered, growable sequence
List is the collection you'll use most. It keeps things in the order you
put them in, lets you fetch by index, and grows as you add:
List<Ticket> tickets = new ArrayList<>();
tickets.add(new Ticket(ana, DayOfWeek.TUESDAY));
tickets.add(new Ticket(luis, DayOfWeek.TUESDAY));
Ticket first = tickets.get(0);
System.out.println(tickets.size()); // 2
Two types appear in that first line, and the split is deliberate: List is
an interface — a promise that you can add, get by index, and iterate, the
same "can do X" idea Priceable covered in Part 4. ArrayList is the
implementation actually holding the data, backed by a plain array it resizes
for you behind the scenes. You declare the variable as the interface and
construct the implementation, exactly like Priceable priceable = new Ticket(...) — the rest of your method only ever talks to List, so you
could swap in LinkedList later without changing a single call site. In
practice you'll write ArrayList well over ninety percent of the time; it's
the right default unless you've measured a reason to switch.
GroupBooking from Part 4 gets simpler for it:
public class GroupBooking implements Priceable {
private final List<Ticket> tickets = new ArrayList<>();
public void add(Ticket ticket) {
tickets.add(ticket);
}
@Override
public double price() {
double total = 0;
for (Ticket ticket : tickets) {
total += ticket.price();
}
return total;
}
}
No more varargs constructor, no more fixed size. Bookings can grow for as long as the program runs.
Generics: the container knows what it holds
That <Ticket> in List<Ticket> is a generic type parameter, and it's worth
being precise about what it buys you, because "generics" gets explained
academically far more often than it needs to. Before Java 5, collections
held plain Object — anything at all — and you cast on the way out:
List old = new ArrayList(); // pre-generics: holds anything
old.add(new Ticket(ana, DayOfWeek.TUESDAY));
old.add("oops, a string"); // compiles fine — old is untyped
Ticket t = (Ticket) old.get(1); // compiles fine, blows up at runtime:
// ClassCastException: String cannot be cast to Ticket
Both of those bugs are invisible until the line that crashes runs — which,
in a large enough codebase, might be weeks after the line that caused them.
List<Ticket> closes the gap by making the container's contents part of its
type: the compiler rejects tickets.add("oops") outright, and get(0)
already comes back typed as Ticket, no cast needed. The mistake still
exists as a mistake, but it moves from a stack trace in production to a red
squiggle in your editor, which is the entire point of a type system. Think
of <Ticket> less as syntax to memorize and more as labeling the box before
you fill it, so nobody — including future you — puts the wrong thing in.
You'll also see generic type parameters on classes you write yourself later
in this series — a Repository<Customer> in Part 10 is the same idea,
just applied to your own container instead of ArrayList.
Map: look things up by key instead of by position
A List finds things by position. Plenty of real lookups aren't positional
at all — find the customer with this email, find the ticket for this
confirmation code. That's Map<K, V>: a key type, a value type, and
constant-time lookup by key instead of scanning.
Map<String, Customer> customersByEmail = new HashMap<>();
customersByEmail.put("[email protected]", ana);
customersByEmail.put("[email protected]", luis);
Customer found = customersByEmail.get("[email protected]");
System.out.println(customersByEmail.containsKey("[email protected]")); // false
Two generic parameters this time instead of one — the key type and the
value type both get labeled, so get() hands back a Customer without a
cast and put("x", 42) won't compile. HashMap is the default
implementation, same relationship to Map that ArrayList has to List.
One sharp edge worth knowing before it bites you: get() on a missing key
returns null rather than throwing, and that null will happily travel two
or three method calls before it becomes a NullPointerException somewhere
that gives you no clue it started at a missing map entry. containsKey()
first, or getOrDefault(key, fallback), are how I've actually seen that
avoided rather than debugged after the fact.
Set: a collection that refuses duplicates
Set<E> is a List that enforces uniqueness — add the same value twice and
the second add() is a no-op. Useful anywhere "has this already happened"
matters more than "in what order":
Set<String> bookedEmails = new HashSet<>();
bookedEmails.add("[email protected]");
bookedEmails.add("[email protected]"); // ignored, already present
System.out.println(bookedEmails.size()); // 1
I reach for this constantly for exactly that shape of problem — has this customer already booked this showtime, has this ID already been processed — where the alternative is a manual loop checking every existing element for a match, which is more code and easier to get wrong than a data structure whose entire job is refusing the duplicate for you.
Walking through a collection
The for loop from Part 3 works on any of these — for (Ticket t : tickets)
is the same for-each syntax whether tickets is a List, the values of a
Map, or a Set. Under the hood, that loop is calling .iterator() and
asking it for the next element each time around, which matters the moment
you need to remove something while iterating: calling tickets.remove(t)
inside a for-each throws ConcurrentModificationException, because you just
changed the thing the iterator is walking. Reach for Iterator directly when
that's genuinely what you need:
Iterator<Ticket> it = tickets.iterator();
while (it.hasNext()) {
Ticket t = it.next();
if (t.price() == 0.0) {
it.remove(); // safe — the iterator owns the removal
}
}
I don't reach for this often, but the one time you need it, nothing else works, so it's worth knowing it exists rather than fighting the exception.
A first taste of streams
The for loop that totals up GroupBooking's prices is a pattern you'll
write a hundred times in slightly different shapes: walk a collection, do
something to or with each element, combine the results. Java 8 gave that
pattern its own syntax — a stream — and once you've internalized the
loop version, the stream version is mostly a change in spelling:
double total = tickets.stream()
.mapToDouble(Ticket::price)
.sum();
List<Ticket> weekdayTickets = tickets.stream()
.filter(t -> t.price() > 0.0)
.collect(Collectors.toList());
stream() turns the collection into a pipeline; filter keeps elements
matching a condition; map (or mapToDouble for primitives) transforms
each one; collect or sum pulls the pipeline back into a concrete result.
Ticket::price is a method reference — shorthand for t -> t.price(), the
lambda syntax briefly mentioned back in Part 3. Nothing here does anything
the for loop couldn't; streams read better once a pipeline has three or
four steps chained together, and worse once you're debugging one at 2am and
wishing you had a line number. I write both, depending on which is more
readable for the specific case — a stream for a genuine transform-and-collect,
a plain loop the moment there's a side effect or a break condition involved.
What to take away
List<Ticket> for an ordered group you'll index or iterate; Map<K, V> when
you're looking things up by key instead of by position; Set<E> when
duplicates are the bug you're trying to prevent. All three are generic, and
that's not decoration — it's the compiler catching the wrong type in your
editor instead of a customer hitting a ClassCastException in production.
ArrayList and HashMap cover the large majority of real code; reach for
anything more specialized only once you've measured an actual reason to.
Take GroupBooking, drop the array, and rebuild it on List<Ticket> the way
this post did. Then add a Map<String, Customer> for looking bookings up by
email, and a Set<String> to stop the same customer from being added twice.
Once that's solid, try writing price() both ways — the for loop and the
stream — and see which one you'd rather find in a code review six months
from now.
That closes out the fundamentals arc — variables and control flow, classes
and objects, now collections and generics. Next up, we step outside a single
file and look at how a real Java project is actually built: Maven and
Gradle, and what they're doing for you that javac alone doesn't.