这似乎是一个基本问题,但它确实让我感到困惑。我想表示一个图的邻接表。我有两个问题:
public class Graph
{
private final int V;
private List<Integer>[] adj;
public Graph(int V)
{
this.V = V;
this.adj = (List<Integer>[]) new LinkedList[V]; // this works
}
}
问题 1:当我执行以下操作时,出现错误提示
Array type expected; found: 'java.util.LinkedList<java.lang.Integer>'
this.adj = (List<Integer>[]) new LinkedList<Integer>()[V];
我正在创建一个整数数组列表,对吗?
问题 2:当我这样做时,它再次给出一个错误,提示创建通用数组:
this.adj = (List<Integer>[]) new LinkedList<Integer>[V];
最后两种方法有什么问题?我认为第一个更正确。
最佳答案
在 (1) 中,您的表达式被解析为
(new LinkedList<Integer>())[V]
正在尝试索引新创建的 LinkedList
,因此出现错误。
在 (2) 中,您试图创建一个泛型数组。 You can't do this .相反,请考虑使用某种容器类型(例如 ArrayList<List<Integer>>
)。
关于java - 表示列表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27586826/