Caner
Caner

Reputation: 59168

List vs ArrayList

List<EventHandler<E>> listeners = new List<EventHandler<E>>();

Why the line above fails with:

Cannot instantiate the type List<EventHandler<E>>

But this one works:

ArrayList<EventHandler<E>> listeners = new ArrayList<EventHandler<E>>();

Upvotes: 1

Views: 10573

Answers (6)

smp7d
smp7d

Reputation: 5032

List is an interface, you can't instantiate an interface.

Upvotes: 15

user650228
user650228

Reputation:

List cannot be instantiated, as it's just an interface.

However, you potentially have another problem as well.

Do you really have a class called 'E'? If you do, well, you shouldn't without a very good reason.

Single letters such as E and T are pretty much exclusively used to denote a generic type parameter. Read it as: "This is a general description of how to make a class or method, without any reference to any specific type - you can parameterize this class by any legal reference type".

So even classes like ArrayList<T> cannot be instantiated - because they are generic "recipes" for classes, not real concrete classes.

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94635

The List<T> is an interface so you can't instantiate it where as ArrayList<T> is a concrete class which is an implementation of List<T>.

Upvotes: 2

Bozho
Bozho

Reputation: 597046

The proper way is:

List<EventHandler<E>> listeners = new ArrayList<EventHandler<E>>();
  • refer to an object by its interface (List)
  • instantiate the object with its concrete type (ArrayList) (interfaces can't be instantiated)

Upvotes: 28

Dyonisos
Dyonisos

Reputation: 3539

List is only an Interface which is implemented by ArrayList

see: http://download.oracle.com/javase/6/docs/api/java/util/List.html

Upvotes: 1

Markus Lausberg
Markus Lausberg

Reputation: 12257

List is an interface and you can not create an instance of an interface

try

List<EventHandler<E>> listeners = new ArrayList<EventHandler<E>>();

Upvotes: 6

Related Questions