×

java · level 3 · unit 1 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A class leaves a gap where the type goes.

You have used ArrayList<String> and HashMap<String, Integer>. Those angle brackets are generics at work. Someone wrote the list class once, with a gap for the type. You fill the gap each time you make one, and Java checks every item against it.

Write your own with a in angle brackets: static class Box<T>. Inside the class, T stands for whatever type the user picks. A Box<String> holds text, a Box<Integer> holds numbers, and one piece of code serves both.

The <> saves typing when you build one: new Box<>("tea") copies the type from the left side. Put the wrong type in and the program never compiles, so the mistake cannot reach your users.

public class Main {
    static class Box<T> {
        private T item;
        Box(T item) {
            this.item = item;
        }
        T open() {
            return item;
        }
    }
    public static void main(String[] args) {
        Box<String> lunch = new Box<>("cheese sandwich");
        Box<Integer> locker = new Box<>(42);
        String food = lunch.open();
        int number = locker.open();
        System.out.println(food.toUpperCase());
        System.out.println(number + 1);
    }
}

By habit a type parameter is one capital letter: T for type, E for element, K and V for key and value.