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

发布于 2024-12-12 12:29:31 字数 403 浏览 3 评论 0 原文

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)添加到队列的前面?

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);
    }

how would I get addAll(nl) to add the entire collection(List<Node>) to the front of the queue?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寂寞清仓 2024-12-19 12:29:31

事实上,我一直在寻找同样的东西,这对我有用!

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

Actually I was looking for the same thing, and this worked for me!!

samplelist.addAll(0,items); // 0 is the index where items are added on the list
嘿嘿嘿 2024-12-19 12:29:31

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

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

其他向后迭代的方法有:

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

选择适合您情况的一种。

There is nothing built-in. But it is simple to emulate - just iterate the list in reverse order and add the elements. That way they will end up in the queue in the right order.

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

Other ways to iterate backwards are:

  • LinkedList's descending iterator
  • Collections.reverse(..)

Pick one which fits your case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文