Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "new ArrayList<E>" is allowed?

Tags:

java

arraylist

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.

  1. List< ?> l = new ArrayList< ?>(); // not compiled and I may know why
  2. List< E> l = new ArrayList< E>(); // compiled!! WHY??

Could anyone tell me why (2) is allowed??

Really thanks for any information.

like image 995
user3513484 Avatar asked Apr 01 '26 06:04

user3513484


1 Answers

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>();
like image 53
Bohemian Avatar answered Apr 03 '26 21:04

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!