Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java generic class & wildcards

Tags:

java

generics

I have a Box generic class with the following feature:

  • one of the 2 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);

    }

}
like image 353
netalie Avatar asked Dec 20 '22 02:12

netalie


2 Answers

change it to

public void put(Box<? extends T> box) {
    put(box.get());
}
like image 65
ZhongYu Avatar answered Jan 10 '23 02:01

ZhongYu


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 to T

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.

like image 37
Tom Avatar answered Jan 10 '23 04:01

Tom