Java:对队列进行排序 [英] Java: Sorting a queue

查看:830
本文介绍了Java:对队列进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为队列类型创建一个包装器,但每次添加元素时,我都想对内部的所有内容进行排序。主要是整数。我对Collections框架不太熟悉,有什么简单的解决方案吗?

I'm making a wrapper to queue type, but each time I add element, I want to sort everything inside. Mostly it will be Integer. I'm not too familiar with Collections framework, is there any simple solution ?

public class Round<Type> {

    private Queue<Type> qe;

    public Round(){
        this.qe = new LinkedList<Type>();
    }


    public void push(Type p){
        this.qe.offer(p);
        //Collections.sort(this.qe); Here I want to sort this
    }


    public Type pop(){
        return this.qe.poll();
    }
}


推荐答案

是你确定这就是你想要的吗?

Are you sure that is what you want?

每次添加元素时对所有内容进行排序似乎并不明智。

Sorting everything every time you add an element doesn't seem wise.

也许你真的想要 PriorityQueue

如果每次添加一个元素,你重新整理整个元素,你必须非常小心实现不要以<$ c结尾$ c> O(n.log(n))插入时的复杂性...这非常非常糟糕。

If every time you add an element, you re-order the whole thing, you'll have to be extremely careful with the implementation not to end up with O(n.log(n)) complexity on insert... which is very very bad.

取决于实际情况用于支持Queue的数据结构你可以做得比这更好,但它依赖于底层实现,我不建议。

Depending on the actual data structure used to support the Queue you can do better than this, but it's relying on an underlying implementation, which I wouldn't advise.

优先级队列允许排队并在 O(log(n))时间中出列,这对于您必须按随机插入顺序维护的结构非常有效。

A priority queue allows for queing and dequeing in O(log(n)) time, which is quite efficient for a structure you have to maintain in order with random inserts.

这篇关于Java:对队列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆