0

I read Java Criticism about why Type erasure makes java less powerful then some languages in generic. In wiki page, here is one example:

public class MyClass<E> {
    public static void myMethod(Object item) {
        if (item instanceof E) {  //Compiler error
            ...
        }
        E item2 = new E();   //Compiler error
        E[] iArray = new E[10]; //Compiler error
    }
}

I understand why E item2 = new E(); should be compiled error because we really don't know class E before calling them. But I don't know why this line should be error:

if (item instanceof E) {  //Compiler error
   ...
}

Because as I know, when compiling java application, all generic type will replaced by its concreted type. for example:

// all E will be substituted by Integer 
MyClass<Integer> myObject = new MyClass<Integer>(); 

So I don't think why should Java throws compile error at above line.

Trần Kim Dự
  • 5,872
  • 12
  • 55
  • 107
  • 5
    Type erasure means the exact opposite of that. `E` gets substituted by `Object`. – shmosel Feb 12 '17 at 06:24
  • Even without type erasure, there's no guarantee that that constructor even exists for T. OO in java doesn't have a mechanism for defining what constructors look like. – David Ehrmann Feb 12 '17 at 06:28
  • @DavidEhrmann I suspect that's what OP means by "`new E();` should be compiled error because we really don't know class E". (By his own logic, `new E()` is as (in)valid as `new Integer()`.) – shmosel Feb 12 '17 at 06:33
  • I don't really understand this point. I accept that List will become List. but object insides still keep their type. so why `instance_of E` should not work. – Trần Kim Dự Feb 12 '17 at 07:28
  • for example we don't use generic but we use raw list then we insert many objects (of any types). After that, we can get each object and use instance_of operator. why this shouldn't work for generic. – Trần Kim Dự Feb 12 '17 at 07:31
  • If `E` becomes `Object`, `instanceof E` would become `instanceof Object`, which is obviously pointless. – shmosel Feb 12 '17 at 12:12
  • What should `item instanceof E` mean? As far as `MyClass` is concerned, `E` is any subclass of `Object`. Therefore `item instanceof E` can only mean `item instanceof Object`. But this test is completely useless - any `item` is always an `instanceof Object`! – Thomas Kläger Feb 12 '17 at 15:46

0 Answers0