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

3

7

I got a strange compiler error when using generics within a for-each loop in Java. Is this a Java compiler bug, or am I really missing something here?

Here is my whole class:

public class Generics<T extends Object> {
  public Generics(T myObject){
    // I didn't really need myObject
  }

  public List<String> getList(){
    List<String> list = new ArrayList<String>();
    list.add("w00t StackOverflow");
    return list;
  }

  public static void main(String...a){
    Generics generics = new Generics(new Object());
    for(String s : generics.getList()){
      System.out.println(s);
    }
  }
}

The compiler is complaining about the line with the for-each: "Type mismatch cannot convert from element type Object to String."
If I make this subtle change, it compiles:

public static void main(String...a){
  Generics<?> generics = new Generics(new Object());
  for(String s : generics.getList()){
    System.out.println(s);
  }
}

I know getList() does use generics, but it uses them in what I thought was a completely unrelated way. I could understand this if I were trying to iterate over something of type T and getList() returned a List<T> or something, but that's not the case here. The return type of getList() should have absolutely nothing to do with T and shouldn't care whether I use the raw type for my Generics object or not...right? Shouldn't these be completely unrelated, or am I really missing something here?

Note that the code also compiles if I do this, which I thought should have been equivalent to the first as well:

public static void main(String...a){
  Generics generics = new Generics(new Object());
  List<String> list = generics.getList();
  for(String s : list){
    System.out.println(s);
  }
}
Proudlove answered 25/3, 2011 at 18:34 Comment(4)
<T extends Object> is no different than <T>. You are not making a generic version of you class, you are making the raw type. Which brings us to the question of why is your class generic in the first place? The only place you use T is in the constructor and you don't use that reference.Constrictor
I used <T extends Object> because I just needed something for an example. The real code obviously is something else, and it does use T...it just uses T in a way completely unrelated to getList().Proudlove
unrelated to your question, but i'd make the constructor be Generics<Class<T> cls) so that you don't have to instantiate an object of type T just to construct this Generics class.Packer
I really just wanted to demonstrate <T extends *something*> without putting the focus on what that something was, so I picked Object for my example.Proudlove
A
12

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!

Abbyabbye answered 25/3, 2011 at 18:41 Comment(4)
I'm very surprised that all the generic references within the member signatures are converted to their raw forms. What is the reasoning for doing that (besides that Sun just felt like it)?Proudlove
@Michael: The JLS includes this discussion in section 4.8 (raw types): "Raw types are closly related to wildcards. Both are based on existential types. Raw types can be thought of as wildcards whose type rules are deliberately unsound, to accommodate interaction with legacy code." In other words, raw types really shouldn't usually appear in new code, but they tried to avoid making old code fail to compile, even if it was at least suspicious.Abbyabbye
Very interesting. I already knew to avoid using raw types (a coworker wrote the code to declare the variable), but this highlights that it really can matter.Proudlove
@michael-mcgowan I guess at one point they got really tired with the immense details of generics, and this is where they think they can cut corners and save some of their time. Had they had more time/energy, they wouldn't leave it in such a sloppy state.Excommunicate
S
3

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>.

Selective answered 25/3, 2011 at 18:40 Comment(3)
Generics is NOT going to be generic of type String...that's the whole point. String is unrelated to the type of Generics. Regardless of T the getList() should return a List<String>.Proudlove
@Michael McGowan, good point. But there has to be some type associated with the type parameter at the point of declaration. Generics<?> generics = new Generics(...); would be fine, modulo an unsafe conversion warning.Selective
@Michael McGowan, note that if all you did was remove the type parameter <T extends Object> from the class declaration, then it would work.Selective
A
-1

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);
    }
  }
Autonomic answered 25/3, 2011 at 18:42 Comment(3)
Generics is NOT going to be generic of type String...that's the whole point. String is unrelated to the type of Generics.Proudlove
I think you misunderstood my point. If you look at the code, you have getList() method returning a List<String>. If we wanted to make the code really clean we could have stripped the generics part from the code other then in the getList() method. you were asking for help to get this to compile rather then was his approach right/wrong.Autonomic
If you leave the generic deceleration on the class level, you open up the getList() method to remove the hard coding that exists now.Autonomic

© 2022 - 2024 — McMap. All rights reserved.