java 列表与数组列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7726361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:08:41  来源:igfitidea点击:

List vs ArrayList

javagenerics

提问by Caner

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

Why the line above fails with:

为什么上面的行失败:

Cannot instantiate the type List<EventHandler<E>>

无法实例化类型 List<EventHandler<E>>

But this one works:

但是这个有效:

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

回答by Bozho

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)
  • 通过接口引用对象 ( List)
  • 使用其具体类型 ( ArrayList)实例化对象(接口无法实例化)

回答by smp7d

Listis an interface, you can't instantiate an interface.

List是一个接口,你不能实例化一个接口。

回答by Markus Lausberg

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

List 是一个接口,你不能创建一个接口的实例

try

尝试

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

回答by adatapost

The List<T>is an interfaceso you can't instantiate it where as ArrayList<T>is a concreteclass which is an implementation of List<T>.

List<T>是一个接口,所以你不能实例化它,因为它ArrayList<T>是一个具体的类,它是List<T>.

回答by kittylyst

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

List 不能被实例化,因为它只是一个接口。

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.

你真的有一个叫做'E'的类吗?如果你这样做,那么,你不应该没有很好的理由。

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

E 和 T 等单个字母几乎专门用于表示泛型类型参数。将其阅读为:“这是对如何创建类或方法的一般描述,没有对任何特定类型的任何引用 - 您可以通过任何合法的引用类型来参数化此类”。

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

所以即使像 ArrayList <T这样的类>也不能被实例化——因为它们是类的通用“配方”,而不是真正的具体类。

回答by Dyonisos

List is only an Interface which is implemented by ArrayList

List 只是一个接口,由 ArrayList 实现

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

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