Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw to <? extends Object>

Tags:

java

generics

I just don't understand this.

List list = new ArrayList();
List <? extends Object> list1 = list; // unchecked conversion warning.

Since Object is the highest upper bound in Java, I don't see any reason why the warning is there.

Update 1:

With regard to akf's answer:

I understand perfectly what you are saying. I already know that. But <? extends Object> is the highest upper bound. Which means you are have any type too you want. Basically <?> == <? extends Object>.

You can try this on your code and you will see <?> == <? extends Objects>

Update 2:

With regard to Sheng's answer:

List  list = new ArrayList ();
List.add("a");
List <? extends Runnable> list1 = list; //warning here

Why no warning here?

List <?> list2 = list; // No warning here

Update 3:

I'm just revisiting the above and still puzzled.

Since the following is permitted by the compiler:

  1. List a = new ArrayList();

  2. List <?> b = a;

  3. List <? extends Object> c = a; // with warning of course

    for (Object obj : b) {}
    // I don't agree with your statements above that &lt;?&gt; cannot be 
    
    // written in the for (:) loop as shown here
    for (Object obj : c) {}
    

Both are permissible. So i still don't see why the unchecked warning when assiging raw to <? extends Object>

like image 595
yapkm01 Avatar asked Aug 22 '10 23:08

yapkm01


2 Answers

This question, and in particular this answer, have some more details on the differences between ? and ? extends Object. I still haven't found anything that says why you get a warning assigning from List to List<? extends Object>, though.

like image 134
Matt McHenry Avatar answered Oct 17 '22 04:10

Matt McHenry


If I'm thinking correctly, then by default the compiler assumes you mean this

List<?> list = new ArrayList();

The ? means that you can have any generic type you want. This is why

List list = new ArrayList();
List <?> list2 = list

works, because for the compiler they are the same thing

However, when you do this

List<?> list = new ArrayList();
List<? extends Object> list2 = list

You're limiting its scope. Because you are limiting the scope, you get a warning. Yes, I know that you don't think you are, but to the compiler you are. If you're absolutely sure you know what your doing, just ignore it or suppress it

like image 43
TheLQ Avatar answered Oct 17 '22 06:10

TheLQ