English 中文(简体)
Java Generics - No Cast
  • 时间:2024-12-22

Java Generics - No Cast


Previous Page Next Page  

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