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

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

我面临以下错误:

不能实例化List<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");

其他回答

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

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

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

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

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

List是一个接口,你不能实例化一个接口,因为接口是一个约定,什么方法应该有你的类。为了实例化,您需要该接口的一些实现(实现)。尝试下面的代码与非常流行的List接口实现:

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

or

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

我们创建soyuz-to是为了简化一个问题:如何将X转换为Y(例如,字符串转换为整数)。构造一个对象也是一种转换,所以它有一个简单的函数来构造Map, List, Set:

import io.thedocs.soyuz.to;

List<String> names = to.list("John", "Fedor");

请检查它-它有很多其他有用的功能

在大多数情况下,您需要简单的ArrayList—List的实现

JDK版本7之前

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

JDK 7及以后版本可以使用菱形操作符

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

进一步的信息写在这里Oracle文档-集合

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

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");