List vs ArrayList

后端 未结 6 557
春和景丽
春和景丽 2021-01-23 20:31
List> listeners = new List>();

Why the line above fails with:

Cannot in

相关标签:
6条回答
  • 2021-01-23 20:44

    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)
    0 讨论(0)
  • 2021-01-23 20:45

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

    0 讨论(0)
  • 2021-01-23 20:48

    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.

    0 讨论(0)
  • 2021-01-23 20:58

    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>.

    0 讨论(0)
  • 2021-01-23 20:59

    List is only an Interface which is implemented by ArrayList

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

    0 讨论(0)
  • 2021-01-23 21:05

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

    try

    List<EventHandler<E>> listeners = new ArrayList<EventHandler<E>>();
    
    0 讨论(0)
提交回复
热议问题