0

I am passing an List with generic type to a method method. Normally Java checks these generic types. But if the method is on a class which itself has a generic type, it does not detect the problem:

import java.util.List;
import java.util.ArrayList;

public class SODemo {
  public static void main(String[] args) {
    List<ClsAlpha> list = new ArrayList<>();
    (new OtherCls()).method(list);
    System.out.println(list.get(0));
  }
}

// Without this <T> the problem IS detected
class OtherCls<T> {
  public void method(List<ClsBeta> list) {
    list.add(new ClsBeta());
  }
}

class ClsAlpha {}
class ClsBeta {}

For me, this code compiles and runs. If the <T> is removed, it doesn't compile.

I am surprised about both: I would expect Java to detect the mismatch in arguments. And I would expect that, if it does compile, it will raise a ClassCastException (I know type information is erased, but I thought there would be casts in the compiled code).

Can anyone enlighten me?

SOLUTION: if an object accepts a generic type T but an instance isn't given one, then all generic types (not only T, also others) for it's arguments are erased. So in the code, OtherCls is raw type, therefore public void method(List<ClsBeta> list) is really public void method(List list). Details in the question that this turned out to be a duplicate of.

Mark
  • 18,730
  • 7
  • 107
  • 130

0 Answers0