Java:如何将addAll(Collection<>)添加到队列的前面?

6
public void traverse(Node root){
    ArrayDeque<Node> queue = new ArrayDeque<Node>();
        queue.add(root);

    while(!queue.isEmpty()){
        Node currentNode = queue.pollFirst();   
        List<Node> nl = getChildrenfromDB(currentNode);
        queue.addAll(nl);
    }

我该如何让addAll(nl)将整个集合(List<Node>)添加到队列的前面?

2个回答

12

其实我也在寻找同样的东西,这个方法对我有用!

samplelist.addAll(0,items); // 0 is the index where items are added on the list

1
这个 addAll 变体在 java.util.AbstractList 中可用,但在 java.util.ArrayDeque 中不可用。 - Kenston Choi

8

没有内置的功能。但是可以很容易地模拟 - 只需按相反的顺序迭代列表并添加元素。这样它们就会以正确的顺序进入队列。

for (int i = list.size() - 1; i >=0; i--) {
    queue.addFirst(node);
}

迭代后退的其他方法包括:

  • LinkedList 的降序迭代器
  • Collections.reverse(..)

选择适合您情况的方法。


1
这难道比addAll()更慢吗? - KJW
1
是的,但我想保留集合的顺序,并将整个集合放在队列中其他元素的前面。 - KJW
2
这就是为什么你应该以相反的顺序进行迭代,以便最终回到初始顺序。 - Bozho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接