I am studying "Java in a Nutshell" 5th Edition. In p169, it says "Remember, though, that type variables exist only at compile time, so you can’t use a type variable with the runtime operators instanceof and new.". If I understand it correctly (Am I??), new and instanceof should not be used with type variables. But after I did some tests, I became more confused.
Could anyone tell me why (2) is allowed??
Really thanks for any information.
The statement "you can't use type variable with new" means you can't do this:
E e = new E(); // can't do this
But you can pass a type variable through to another class for it to use:
class MyClass<E> {
List<E> = new ArrayList<E>(); // OK
}
You're not instantiating E, you're instantiating an ArrayList with the type E.
Regarding using ?, that's a different issue. The ? means "unknown" type, while a variable can be of an unknown type, you can't instantiate a generic class by specifying unknown type - you must pass a known type through to the generic class.
You can however code this:
List<?> list = new ArrayList<E>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With