Advanced Java: Collections, Generics and More ยท Generics
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.
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);
}
}Box() has finished, so its variables are gone.put(), with item = "hello". It gets its own variables on the stack.put() has finished, so its variables are gone.take() has finished, so its variables are gone.w.Box() has finished, so its variables are gone.put(), with item = 42. It gets its own variables on the stack.item in the Box that numbers points to changes from null to 42.put() has finished, so its variables are gone.take(). It gets its own variables on the stack.take() has finished, so its variables are gone.n.hello 42.