2017-04-20 77 views
1

如何使用集合在Java中创建链接列表的向量? 到目前为止,我已经写了下面的代码:链接列表向量

Vector <LinkedList <Integer> > adj = new Vector<>(); 

但我无法弄清楚如何初始化链表的头节点的载体。

我想给出一个整数n什么,我希望与值0作为头节点初始化向量N-1:

e.g given N = 4 

vector ---> 0 
      1 
      2 
      3 

这样,以后我可以添加成员名单时,需要这样的:

vector ---> 0->2->3 
      1->3 
      2->0->1 
      3->1 
+2

您可以像您一样创建一个'Vector',然后根据需要添加尽可能多的空'LinkedList'对象。但首先,你为什么要使用“Vector”?这听起来很像一个[XY问题](http://xyproblem.info) –

+0

这是对@ JimGarrison的评论wrt的解释。 'VECTOR'。从'Vector'的Javadoc:[“如果不需要线程安全的实现,建议使用'ArrayList'来代替'Vector'。”](https://docs.oracle.com/javase/ 8 /文档/ API/JAVA/util的/ Vector.html) – Turing85

回答

1

随着你写的代码,你已经创建了一个空载体 - 你有LinkedList的实例的所需数量来填补它(我猜你是一个C++程序员,其中矢量将初始化“自动化” ically“?)。例如。初始化您的载体是这样的:

int N = 4; 
Vector<LinkedList<Integer>> adj = new Vector<>(N); // N here isn't really needed, but it sets the initial capacity of the vector 
for (int i = 0; i < 4; i++) { 
    ajd.add(new LinkedList<>()); 
} 

此外,作为Turing85指出,你应该使用ArrayList如果你并不需要同步。