← Learning Hub
Beginner

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.

Example
You can edit this code.

Sort a list with a Comparator:

Example
You can edit this code.
The <> on the right ("diamond") lets Java work out the type for you.
Key points
  • 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.sort or a Comparator.

📝 Test yourself

1. Which collection does not allow duplicates?
2. Which collection stores key and value pairs?
3. Fill in the method that adds an item to a list:
cart.("Bag");