Generics and Collections
Collections store groups of objects. Generics (the <Type> part) say what type they hold, so mistakes are caught early.
List(e.g.ArrayList): ordered, allows duplicates.Set(e.g.HashSet): no duplicates.Map(e.g.HashMap): key and value pairs.
Arrays in Java have a fixed size. Real data grows and shrinks - items are added to carts, users sign up, orders are cancelled. The Collections Framework gives you ready-made, well-tested containers that resize themselves and come with methods for adding, removing, searching and sorting.
Choosing the right one is a key skill: use a List when order matters or duplicates are allowed (a cart), a Set when each item must be unique (registered emails), and a Map when you look things up by a key (product code -> product). The interface (List) is on the left, the actual class (ArrayList) on the right, so you can change the class later without changing the rest of the code.
Generics make collections type-safe. List<String> can only hold Strings, so the compiler stops you from adding a number by mistake, and you never need to cast when reading items back.
Sort a list with a Comparator:
<> on the right ("diamond") lets Java work out the type for you.- List (ordered, duplicates), Set (unique), Map (key -> value).
- Generics like
List<String>make collections type-safe. - Declare with the interface, create with the class:
List<String> x = new ArrayList<>(); - Sort with
Collections.sortor a Comparator.
