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

KJW*_*KJW 5 java collections arraydeque

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);
    }
Run Code Online (Sandbox Code Playgroud)

如何将addAll(nl)整个collection(List<Node>)添加到队列的前面?

aze*_*ati 10

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

samplelist.addAll(0,items); // 0 is the index where items are added on the list
Run Code Online (Sandbox Code Playgroud)

  • 这省了我很多头疼,非常感谢 (2认同)

Boz*_*zho 8

内置任何东西都没有.但是模拟很简单 - 只需按相反的顺序迭代列表并添加元素.这样他们就会以正确的顺序排在队列中.

for (int i = list.size() - 1; i >=0; i--) {
    queue.addFirst(node);
}
Run Code Online (Sandbox Code Playgroud)

其他迭代迭代的方法是:

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

选一个适合你的情况.

  • 不.addAll做同样的事情(在大多数情况下).这是O(n) (2认同)
  • 这就是为什么你应该以相反的顺序迭代,以便它以最初的顺序结束 (2认同)