Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 544
user2653926 Avatar asked Mar 16 '26 02:03

user2653926


1 Answers

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!

like image 107
fge Avatar answered Mar 18 '26 16:03

fge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!