user2653926
user2653926

Reputation: 604

generics unchecked warning conversion

I have read in generics that "? extends Object" and "?" are synonymous then why this occurs.

List list=new ArrayList();
List<? extends Object> list2=list;     //1
List<?> list3=list;                    //2

For 1 unchecked conversion warning is thrown but not for 2. So the compiler somewhere is definitely differentiating between the two. Plz explain the difference between the two with respect to the above code

Upvotes: 3

Views: 86

Answers (2)

Ivan Mamontov
Ivan Mamontov

Reputation: 2924

Because some type information is erased during compilation, not all types are available at run time. Types that are completely available at run time are known as reifiable types(see http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.7).

So according to JLS List<?> is a reifiable type, but List<? extends Object> is not, which means they are not the same from compiler point of view.

Upvotes: 0

fge
fge

Reputation: 121720

I have read in generics that "? extends Object" and "?" are synonymous

Not quite. The first wildcard has a lower bound, the second does not. For your two examples it should not make a difference (well, except that you can only add null to list2 and list3!).

This lower bound can make a difference: "erasure signature" (I don't know the exact term).

The best example for this is Collections.max(); you will notice that the parameter type is defined as T extends Object & Comparable<? super T>.

This is because prior to Java 5 this method existed and was defined as:

static Object max(Collection coll)

If the type parameter were defined as T extends Comparable<? super T>, this would have meant that the method in 1.4 would have had to return a Comparable!

Upvotes: 2

Related Questions