I have a Box generic class with the following feature:
put
methods should allow a client to insert a box and get its content to the current box.I want this method to get 2 types of boxes: Box<Number>
and Box<Integer>
, that is why I changed the put(Box<T>)
method to put(Box<? extends Number> box)
. But I get compilation warning. What am I doing wrong here?
This is my current code: the warning i get is: Type safety: Unchecked cast from capture#1-of ? extends Number to T
public class Box<T> {
public T get() {
return element;
}
public void put(T element) {
this.element = element;
}
public void put(Box<? extends Number> box) {
put((T) box.get()); // this is where i get the warning
}
private T element;
}
public class BoxClient {
public static void main(String[] args) {
Box<Number> nBox = new Box<Number>();
Box<Integer> iBox = new Box<Integer>();
nBox.put(iBox);
}
}
change it to
public void put(Box<? extends T> box) {
put(box.get());
}
If I test your code, then I get a warning in this method:
public void put(Box<? extends Number> box) {
put( (T) box.get());
}
And the warning is:
Unchecked cast:
java.lang.Number
toT
The problem is that your generic type T
has no bounds, so it can be anything and due to the type erasure it will be erased to Object
.
The generic type of the variable box
has a bound, so it is clear, that it will always be some kind of Number
.
Your cast (T) box.get()
is now "unsafe", because box.get()
returns a subtype of Number
and T
can be anything, like a String
. So the compile can't be sure that this cast will always be ok and won't throw a ClassCastException
.
That is why he is warning you about your unsafe cast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With