0

i have a problem that stunned me a lot.

I have a class (Bar) with a getter method which returns a List:

public abstract class Bar<T extends IdentifiableObject> {
...
public List<Bar> getBars() {
    return bars;
}
...

The hierarchy i have is:

public abstract class Bar<T extends IdentifiableObject>;
public abstract class IdentifiableObject<T extends Comparable<T>>;

Until here everything works fine, the problem is when I execute:

for(Bar bar : bars.getBars()) {
}

The previous sentence throws a compilation error:

incompatible types: java.lang.Object cannot be converted to java.util.List<com.x.Bar>

I was suprised with this error but i was more suprised when i performed

List<Bar> bars = bar.getBars();
Iterator<Bar> iterator = bar.getBars().iterator();

both without problems

What is wrong here in the "for" sentence?

Thank you

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 11
    Basically this is because you're using the raw type `Bar` instead of a parameterized version. Avoid raw types like the plague. – Jon Skeet Dec 15 '14 at 11:09
  • 1
    You haven't said what `bars` is in your `for` example, but Jon's comment above is almost certainly the issue regardless. – T.J. Crowder Dec 15 '14 at 11:14
  • 1
    Java doesn't like mixing raw types with generics. Try to use one or the other. If you don't need the generics (as you don't appear to be using `Bar` but rather `Bar`) take the generics out. – Peter Lawrey Dec 15 '14 at 11:17
  • I know i shouldn't use raw types, but in this method i don't need to know the type of Bar. As you see Bar is abstract and will be implemented specifically in another classes. In this method i don't know what kind of Bar i have, so obiously i dont know the T type of Bar, and even more I don't want to know the type because this class does should not access to it's type. The question I have is... why List bar = ... works and the "for" not? – Javier Molina Alonso Dec 15 '14 at 11:45
  • same isssue here: http://stackoverflow.com/questions/5436656/why-does-the-java-compiler-complain-on-using-foreach-with-a-raw-type (with a ref to java specs from Jon) – syllabus Dec 15 '14 at 16:09

1 Answers1

0

Create an instance of Bar class as below:

Bar<?> bar = new Bar();

Add the above line before your code

List<Bar> bars = bar.getBars();
Iterator<Bar> iterator = bar.getBars().iterator();
Awanish
  • 327
  • 1
  • 3
  • 14