3 回答

TA贡献1942条经验 获得超3个赞
如果您检查API,List则会注意到它说:
Interface List<E>
作为一种interface手段,它无法实例化(new List()不可能)。
如果您检查该链接,则会发现一些class实现的List:
所有已知的实施类:
AbstractList,AbstractSequentialList,ArrayList,AttributeList,CopyOnWriteArrayList,LinkedList,RoleList,RoleUnresolvedList,Stack,Vector
那些可以实例化。使用它们的链接来了解有关它们的更多信息,即IE:以了解哪个更适合您的需求。
三种最常用的可能是:
List<String> supplierNames1 = new ArrayList<String>();
List<String> supplierNames2 = new LinkedList<String>();
List<String> supplierNames3 = new Vector<String>();
奖励:
您还可以使用,以更简单的方式使用值实例化它Arrays class,如下所示:
List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));
但是请注意,您不允许向该列表添加更多元素fixed-size。

TA贡献1850条经验 获得超11个赞
无法实例化接口,但实现很少:
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");

TA贡献1856条经验 获得超5个赞
List是一个Interface,您不能实例化一个Interface,因为interface是一个约定,什么样的方法应该具有您的类。为了实例化,您需要该接口的一些实现(实现)。尝试使用下面的代码以及非常流行的List接口实现:
List<String> supplierNames = new ArrayList<String>();
要么
List<String> supplierNames = new LinkedList<String>();
添加回答
举报