如何在Java中初始化List <String>对象?

本文翻译自:How to initialize List object in Java?

I can not initialize a List as in the following code: 我无法初始化List,如下面的代码所示:

List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));

I face the following error: 我面临以下错误:

Cannot instantiate the type List<String> 无法实例化类型List<String>

How can I instantiate List<String> ? 如何实例化List<String>


#1楼

参考:https://stackoom.com/question/uCgE/如何在Java中初始化List-String-对象


#2楼

You will need to use ArrayList<String> or such. 您将需要使用ArrayList<String>等。

List<String> is an interface. List<String>是一个接口。

Use this: 用这个:

import java.util.ArrayList;

...

List<String> supplierNames = new ArrayList<String>();

#3楼

List is an interface, and you can not initialize an interface. List是一个接口,您无法初始化接口。 Instantiate an implementing class instead. 实际上实例化一个实现类。

Like: 喜欢:

List<String> abc = new ArrayList<String>();
List<String> xyz = new LinkedList<String>();

#4楼

List is an Interface , you cannot instantiate an Interface, because interface is a convention, what methods should have your classes. List是一个接口 ,你不能实例化一个接口,因为接口是一个约定,你的类应该有哪些方法。 In order to instantiate, you need some realizations(implementations) of that interface. 为了实例化,您需要该接口的一些实现(实现)。 Try the below code with very popular implementations of List interface: 使用非常流行的List接口实现尝试以下代码:

List<String> supplierNames = new ArrayList<String>(); 

or 要么

List<String> supplierNames = new LinkedList<String>();

#5楼

Depending on what kind of List you want to use, something like 取决于您要使用的List类型,类似于

List<String> supplierNames = new ArrayList<String>();

should get you going. 应该让你去。

List is the interface, ArrayList is one implementation of the List interface. List是接口,ArrayList是List接口的一个实现。 More implementations that may better suit your needs can be found by reading the JavaDocs of the List interface . 通过阅读List接口JavaDocs,可以找到更适合您需求的更多实现。


#6楼

List is an Interface . 列表是一个接口。 You cant use List to initialize it. 你不能使用List来初始化它。

  List<String> supplierNames = new ArrayList<String>();

These are the some of List impelemented classes, 这些是列中的一些实例化的类,

ArrayList, LinkedList, Vector

You could use any of this as per your requirement. 您可以根据自己的要求使用其中任何一项。 These each classes have its own features. 这些每个类都有自己的功能。

猜你喜欢

转载自blog.csdn.net/p15097962069/article/details/107634406