【问题标题】:Vector of linked list链表向量
【发布时间】:2017-04-20 19:00:19
【问题描述】:

如何使用 Collections 在 Java 中创建链表向量? 到目前为止,我已经编写了以下代码:

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

但是我无法弄清楚如何用链表的头节点初始化向量。

我想要的是一个整数N,我希望用值0N-1 作为头节点来初始化向量:

e.g given N = 4

vector ---> 0
            1
            2
            3 

以便以后我可以在需要时将成员添加到列表中:

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

【问题讨论】:

标签: java vector collections linked-list


【解决方案1】:

使用您编写的代码,您创建了一个空向量 - 您必须用所需数量的 LinkedList instances 填充它(我猜您是 C++ 程序员,向量将在其中初始化“自动地”?)。例如。像这样初始化你的向量:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-03
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多