如何初始化List< String> Java中的对象? [英] How to initialize List<String> object in Java?
问题描述
我无法按以下代码初始化List:
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));
我遇到以下错误:
无法实例化类型
列表< String>
我如何实例化列表< String>
?
推荐答案
如果你查看 API >列表
你会注意到它:
If you check the API for List
you'll notice it says:
Interface List<E>
作为界面
表示无法实例化(没有新的List()
是可能的。)
Being an interface
means it cannot be instantiated (no new List()
is possible).
如果你检查那个链接,你会发现一些 class
es实现列表
:
If you check that link, you'll find some class
es that implement List
:
所有已知的实施类:
All Known Implementing Classes:
AbstractList
, AbstractSequentialList
, ArrayList
, AttributeList
, CopyOnWriteArrayList
, LinkedList
, RoleList
, RoleUnresolvedList
, Stack
, Vector
AbstractList
, AbstractSequentialList
, ArrayList
, AttributeList
, CopyOnWriteArrayList
, LinkedList
, RoleList
, RoleUnresolvedList
, Stack
, Vector
可以实例化这些。使用他们的链接了解更多关于他们的信息,IE:知道哪个更适合您的需求。
Those can be instantiated. 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));
但请注意,您不能在该列表中添加更多元素,因为它是固定大小
。
But note you are not allowed to add more elements to that list, as it's fixed-size
.
这篇关于如何初始化List< String> Java中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!