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.
Perhaps you actually want a PriorityQueue?
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.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.
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.