-2

I was going through the Java Generics and found the following limitation :-

  1. Create an array of that static type. This one is the most annoying, but it makes sense because you’d be creating an array of Objects.
  2. Call instanceof. This is not allowed because at runtime List<Integer> and List<String> look the same to Java thanks to type erasure. But the following code is compiled fine.

    interface Shippable<T> {
      void ship(T t);
    }
    class ShippableAbstractCrate<H> implements Shippable<H> {
      public void ship(H t) {
        if(t instanceof Object) {
          //do something 
        }
      }
    }
    

3.Create a static variable as a generic type parameter. This is not allowed because the type is linked to the instance of the class.

Can you please provide the clarification with examples. I'm asking why all 3 points are limitation in generics ?

Hasnain Ali Bohra
  • 2,130
  • 2
  • 11
  • 25

1 Answers1

1
  1. means you can't write

    if(t instanceof H)
    

    You can always write if(t instanceof Object)

  2. means you can't define the following static variable in your ShippableAbstractCrate class:

    static H someName;
    
Eran
  • 387,369
  • 54
  • 702
  • 768
  • isn't 2 meant to be (also?) something like `H instanceof String`? – user85421 Jul 18 '17 at 12:30
  • @CarlosHeuberger The first operand of `instanceof` can't be a type anyway, so `H instanceof String` would fail for a different reason, not related to generics at all (just like `Integer instanceof String` would fail, unless you have some variable called `Integer` in scope). – Eran Jul 18 '17 at 12:35
  • but isn't that exactly was is meant, based on the mention that `List` looks the same as `List` at runtime? or should it be `t instanceof List` that is not possible? – user85421 Jul 18 '17 at 12:38