Java Generics - No Cast


Advertisements

Casting to a parameterized type is not allowed unless it is parameterized by unbounded wildcards.

Box<Integer> integerBox = new Box<Integer>();
Box<Number> numberBox = new Box<Number>();
//Compiler Error: Cannot cast from Box<Number> to Box<Integer>
integerBox = (Box<Integer>)numberBox;

To achive the same, unbounded wildcards can be used.

private static void add(Box<?> box) {
   Box<Integer> integerBox = (Box<Integer>)box;
}
Advertisements