【问题标题】:How do I initialise a static List<T>?如何初始化静态 List<T>?
【发布时间】:2011-03-14 13:58:00
【问题描述】:
我似乎无法理解这个声明中出了什么问题
public static List<Vertex> vertices;
// where Vertex is a class with a default constructor
public static void main ( String [] arg ) throws IOException {
vertices = new List<Vertex>(); // eclipse complains
}
我应该在哪里以及如何初始化这个列表.....
因此,当我继续添加到列表中时,它会抱怨空指针异常.....谁能告诉我我做错了什么......
【问题讨论】:
标签:
java
collections
static
initialization
【解决方案1】:
List 是一种抽象类型,由各种类型的列表扩展和实现。
请尝试以下操作:
public static void main ( String [] arg ) throws IOException {
vertices = new ArrayList<Vertex>();
}
【解决方案2】:
List 是一个接口,不能被实例化。请改用 ArrayList 或 LinkedList。
vertices = new ArrayList<Vertex>();
【解决方案3】:
列表是一个接口。您需要使用实现List的类,例如ArrayList。
【解决方案5】:
List 不是类,而是接口。由于接口不是任何可以实例化的东西的完整具体实现。您只能对非抽象类执行新操作。所以尝试实例化ArrayList 或其他实现。
【解决方案6】:
你需要使用一个List的实现,比如:
vertices = new ArrayList<Vertex>();
【解决方案7】:
Eclipse 抱怨是因为 List 不能被实例化,因为它是一个接口而不是一个具体的类。
您在这里有两个选择-
选项 1:
public static List<Vertex> vertices;
// where Vertex is a class with a default constructor
public static void main ( String [] arg ) throws IOException {
vertices = new ArrayList<Vertex>(); // eclipse does not complain
}
选项2:
public static List<Vertex> vertices=new ArrayList<Vertex>();
// where Vertex is a class with a default constructor
public static void main ( String [] arg ) throws IOException {
v
}