我无法像下面的代码那样初始化列表:
List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));我面临以下错误:
无法实例化类型
List<String>
如何实例化List<String>
发布于 2012-11-15 10:07:41
如果您检查API接口中的List,您会注意到它写着:
Interface List<E>作为一个interface意味着它不能被实例化(没有new List()是可能的)。
如果你检查这个链接,你会发现一些classes实现了List
所有已知的实现类:
AbstractList,AbstractSequentialList,ArrayList,AttributeList,CopyOnWriteArrayList,LinkedList,RoleList,RoleUnresolvedList,Stack,Vector
其中一些可以实例化(未定义为abstract class的)。利用他们的链接来了解更多关于他们的信息,即:知道哪一个更适合你的需求。
最常用的三种可能是:
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。
发布于 2017-11-14 14:25:24
无法实例化接口,但实现很少:
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");发布于 2012-11-15 10:02:43
列表是一个接口,您不能实例化一个接口,因为接口是一个约定,哪些方法应该有您的类。为了实例化,您需要实现(实现)该接口。尝试下面的代码,并使用非常流行的列表接口实现:
List<String> supplierNames = new ArrayList<String>(); 或
List<String> supplierNames = new LinkedList<String>();https://stackoverflow.com/questions/13395114
复制相似问题