本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看<活动链接>
问题
按照下面代码,我不能初始化一个 List :
List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));
将会出现下面的错误:
Cannot instantiate the type List<String>
我该如何实例化 List<String> 呢?
回答
回答1
如果您查看 List 的 API,你会注意到:
Interface List<E>
一个接口 interface, 意味着是无法进行实例化的(即:不能进行 new List())
查看 API,则会发现关于 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>();
您还可以使用 Arrays 类以一种更简单的方式根据值来实例化,如下所示:
List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));
但请注意,你不能向该 List 中添加其他更多元素,因为它是固定大小的。
回答2
无法实例化接口,但至少可以实现它:
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");
翻译内容来源Stack Overflow:stackoverflow.com/questions/1…