我不能在以下代码中初始化一个列表:

List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));

我面临以下错误:

不能实例化List<String>类型

我如何实例化列表<字符串>?


当前回答

如果你检查List的API,你会注意到它说:

Interface List<E>

作为一个接口意味着它不能被实例化(不可能有新的List())。

如果你检查这个链接,你会发现一些类实现了List:

所有已知的实现类: AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector

其中一些可以实例化(没有定义为抽象类的那些)。使用他们的链接来了解更多关于他们的信息,即:知道哪个更适合你的需求。

最常用的三种可能是:

 List<String> supplierNames1 = new ArrayList<String>();
 List<String> supplierNames2 = new LinkedList<String>();
 List<String> supplierNames3 = new Vector<String>();

奖金: 你也可以用数组类以更简单的方式实例化它,如下所示:

List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));

但请注意,您不允许向该列表中添加更多元素,因为它是固定大小的。

其他回答

你需要使用ArrayList<String>之类的。

List<String>是接口。

用这个:

import java.util.ArrayList;

...

List<String> supplierNames = new ArrayList<String>();

如果你只想创建一个只有一个对象的不可变List<T>,你可以使用这个API:

List<String> oneObjectList = Collections.singletonList("theOnlyObject”);

更多信息:文档

这取决于你想使用什么样的List,比如

List<String> supplierNames = new ArrayList<String>();

应该能让你走了。

List是接口,ArrayList是List接口的一种实现。通过阅读List接口的JavaDocs,可以找到更多可能更适合您需求的实现。

List只是一个接口,一个通用列表的定义。您需要提供这个列表接口的实现。最常见的两种是:

数组列表——在数组上实现的列表

List<String> supplierNames = new ArrayList<String>();

LinkedList -一个像相互连接的元素链一样实现的列表

List<String> supplierNames = new LinkedList<String>();

不能实例化接口,但有几个实现:

JDK2

List<String> list = Arrays.asList("one", "two", "three");

JDK7

//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");

JDK8

List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());

JDK9

// creates immutable lists, so you can't modify such list 
List<String> immutableList = List.of("one", "two", "three");

// if we want mutable list we can copy content of immutable list 
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));

此外,还有许多其他库提供的其他方法,如Guava。

List<String> list = Lists.newArrayList("one", "two", "three");