Java: Generic casting down generates a warning, why?

I do not understand why the following code generates a warning.

interface Generic<T> { } interface A { } class B { Generic<A> c; <T extends A> B(Generic<T> a) { c = (Generic<A>) a; //warning here } } //Unchecked cast from Generic<T> to Generic<A> 

In class B, I am only interested in instances of Generic that are of type A. This warning suggests that I need to save the general argument as T instead of A.

But this means that I will also have to declare B generic, which seems to complicate the work of what they should be.

+4
source share
2 answers

This is not casting, since the generated Java invariants are: Generic<T> not a subtype of Generic<A> , although T is a subtype of A. If you only need general methods that return A, you can use the Generic<? extends A> Wildcard Generic<? extends A> in constructor B and in the field that stores the link.

+6
source

Because Generic<T> not a subtype of Generic<A> , even if T is a subtype of A

To illustrate this, consider a String instance of Object :

 List<String> listOfStrings = new ArrayList<String>(); List<Object> listOfObjects = (List<Object>)listOfStrings; // invalid listOfObjects.add(new Date()); // now listOfStrings contain a date! 

The compiler does not allow this because it can damage the original list. The JVM does not apply general runtime requirements to boundaries.

The solution here is to declare the field type c as' Generic`.

+5
source

All Articles