1
public class SuperType<T> {

    T var;

    public T getVar(){
        return var;
    }
}

public class SubType extends SuperType<String>{

    public static void main(String args[]){
        List<SuperType<?>> ls = new ArrayList<SubType>();//(1) throwing an error
        List<?> ls1 = new ArrayList<String>();// no error
     }
}

I am trying to figure out why an error is being thrown at (1). Can someone explain this?

rgettman
  • 176,041
  • 30
  • 275
  • 357
vjk
  • 2,163
  • 6
  • 28
  • 42

1 Answers1

1

In Java, generics are invariant. This means that even if SubType is a SuperType<String>, that doesn't mean that a List<SubType> is a List<SuperType<?>> or even a List<SuperType<String>>. That is why (1) is an error. You can resolve this by introducing a wildcard:

List<? extends SuperType<?>> ls = new ArrayList<SubType>();

The second line isn't an error, because the wildcard ? means any type.

Note that using wildcards restricts what can be done with such lists, such as when you call add.

rgettman
  • 176,041
  • 30
  • 275
  • 357