Advanced Java: Collections, Generics and More ยท Generics

Generic Classes

Write one Box class that can hold any type, while the compiler still checks you put in and take out the right kind of thing.

GenericsDemo.java

class Box<T> {
    private T item;

    void put(T item) {
        this.item = item;
    }

    T take() {
        return item;
    }
}

public class GenericsDemo {
    public static void main(String[] args) {
        Box<String> words = new Box<>();
        words.put("hello");
        String w = words.take();          // no cast needed: the box holds Strings

        Box<Integer> numbers = new Box<>();
        numbers.put(42);
        int n = numbers.take();
        System.out.println(w + " " + n);
    }
}

Step by step

  1. Box<String>: in this box, T means String.
  2. Box() has finished, so its variables are gone.
  3. Box<String>: in this box, T means String.
  4. Java calls put(), with item = "hello". It gets its own variables on the stack.
  5. put stores the item. Here T is String.
  6. put() has finished, so its variables are gone.
  7. take returns a String directly: no cast.
  8. take() has finished, so its variables are gone.
  9. The value it returned, "hello", is stored in w.
  10. A second box, this time of Integer. Same class, different T.
  11. Box() has finished, so its variables are gone.
  12. A second box, this time of Integer. Same class, different T.
  13. Java calls put(), with item = 42. It gets its own variables on the stack.
  14. item in the Box that numbers points to changes from null to 42.
  15. put() has finished, so its variables are gone.
  16. Java calls take(). It gets its own variables on the stack.
  17. take() has finished, so its variables are gone.
  18. The value it returned, 42, is stored in n.
  19. It prints hello 42.
  20. "hello" and 42 from the same Box class, each type-checked.