【问题标题】:java: how to addAll(Collection<>) to the front of the queue?java:如何将All(Collection<>) 添加到队列的前面?
【发布时间】:2011-12-18 03:19:19
【问题描述】:
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&lt;Node&gt;)添加到队列的前面?

【问题讨论】:

    标签: java collections arraydeque


    【解决方案1】:

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

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

    【讨论】:

    • addAll 变体在java.util.AbstractList 中可用,但在java.util.ArrayDeque 中不可用。
    【解决方案2】:

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

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

    其他向后迭代的方法是:

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

    选择一个适合您的情况。

    【讨论】:

    • 这不是比 addAll() 慢吗?
    • 是的,但我想保留 Collection 的顺序,只需将整个 Collection 放在队列中其他元素的前面。
    • 这就是为什么你应该以相反的顺序迭代,以便它以初始顺序结束
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多