Why does the Java Compiler complain on using foreach with a raw type? [duplicate]

会有一股神秘感。 提交于 2019-11-29 13:41:44

The difference is that when you use the raw type, all the generic references within the member signatures are converted to their raw forms too. So effectively you're calling a method which now has a signature like this:

List getList()

Now as for why your final version compiles - although it does, there's a warning if you use -Xlint:

Generics.java:16: warning: [unchecked] unchecked conversion
    List<String> list = generics.getList();
                                        ^

This is similar to:

 List list = new ArrayList();
 List<String> strings = list;

... which also compiles, but with a warning under -Xlint.

The moral of the story: don't use raw types!

Mike Samuel

Change the line

Generics generics = new Generics(new Object());

to

Generics<?> generics = new Generics<Object>(new Object());

The root of your problem is that you are using a raw type so the type of the getList method is List, not List<String>.

I made a couple adjustments to your code. You see in your comment you don't need Object in your constructor, so lets remove that to avoid any confusion. Second, if Generics is going to be generic, initialize it properly

Here is what the new main would look like

public static void main(String...a){
    Generics<String> generics = new Generics<String>();
    for(String s : generics.getList()){
      System.out.println(s);
    }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!