如何初始化 List<String>Java中的对象? [英] How to initialize List<String> object in Java?
问题描述
我不能像下面的代码那样初始化一个列表:
I can not initialize a List as in the following code:
List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));
我遇到以下错误:
无法实例化类型List
如何实例化List
?
推荐答案
如果您查看 API for List
你会注意到它说:
If you check the API for List
you'll notice it says:
Interface List<E>
作为 interface
意味着它不能被实例化(没有 new List()
是可能的).
Being an interface
means it cannot be instantiated (no new List()
is possible).
如果你检查那个链接,你会发现一些实现List
的class
:
If you check that link, you'll find some class
es that implement List
:
所有已知的实现类:
AbstractList
、AbstractSequentialList
、ArrayList
、AttributeList
、CopyOnWriteArrayList
、LinkedList
、RoleList
、RoleUnresolvedList
、Stack
、Vector
其中一些可以实例化(未定义为抽象类
的那些).使用他们的链接了解更多关于他们的信息,即:了解哪个更适合您的需求.
Some of those can be instantiated (the ones that are not defined as abstract class
). Use their links to know more about them, I.E: to know which fits better your needs.
最常用的 3 个大概是:
The 3 most commonly used ones probably are:
List<String> supplierNames1 = new ArrayList<String>();
List<String> supplierNames2 = new LinkedList<String>();
List<String> supplierNames3 = new Vector<String>();
奖励:
您还可以使用 Arrays
class
以更简单的方式用值实例化它,如下所示:
Bonus:
You can also instantiate it with values, in an easier way, using the Arrays
class
, as follows:
List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));
但请注意,您不能向该列表添加更多元素,因为它是fixed-size
.
But note you are not allowed to add more elements to that list, as it's fixed-size
.
这篇关于如何初始化 List<String>Java中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!