-2

I can't grasp why my interface parametrization doesn't work. Let's look at code below:

public interface IType {
  public List<String> getAllItems();
}

......
public void function(IType item) {
  for (String str : item.getAllItems()) { //DOESN'T WORK! Incompoatible types. Required String, Found: Object

  } 
}

Why does it return List<Object> instead of List<String>?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
VB_
  • 45,112
  • 42
  • 145
  • 293

1 Answers1

5

I'm going to make an assumption that your IType is actually a parameterized (and you've just confirmed it) type like so

public interface IType<E> {
    public List<String> getAllItems();
}

In this case, if you declare a variable (or parameter) as

IType item;

you are using a Raw Type. With a variable of a raw type, all generic types in methods or fields accessed on that variable are erased. So

public List<String> getAllItems();

becomes

public List getAllItems();

and so the List Iterator will return references of type Object.

public void function(IType item) {
    for (String str : item.getAllItems()) { // DOESN'T WORK! Incompoatible
                                            // types. Required String,
                                            // Found: Object
    }
}

Combining Raw Types and Generic Methods

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724