Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

Блог пользователя gauravmunjal

Автор gauravmunjal, 14 лет назад, По-английски


class PriorityQueue

It BASICALLY KEEPS THE ELEMTS SORTED ACCORDINGLY. THE HEAD OF THE QUEUE IS THE LEAST ELEMENT TO THE SPECIFIED ORDERING. IMPLEMENTATION NOTE: THIS IMPLEMENTATION PROVIDES O(LOG(N)) TIME FOR THE INSERTION METHODS (OFFERPOLLREMOVE() AND ADD) METHODS; LINEAR TIME FOR THE REMOVE(OBJECT) AND CONTAINS(OBJECT) METHODS; AND CONSTANT TIME FOR THE RETRIEVAL METHODS (PEEKELEMENT, AND SIZE).

How will the sorting be done?
This is either naturally specified or otherwise, that depends on the arguments of the constructor. Like if the class Integer is specified then the comparison will be done using the compareTo method of the comparable interface. This is when we do 

PriorityQueue temp = new PriorityQueue();

For adding and removal the methods which are available are : add() and poll() (removes the element from the head of the Queue)

Program
public static void main(String[] args) {
PriorityQueue temp = new PriorityQueue();
temp.add(4); temp.add(2); temp.add(3); temp.add(7); temp.add(1);
while (!temp.isEmpty()) {
System.out.println(temp.poll());
}
}

Output
1
2
3
4
7

This being the case when we use a class which has already implemented the Comparable Interface. 

Now suppose that we have user defined objects to be stored in the PriorityQueue, then for the sorting to be done the user defined class will implement the interface Comparable and override the compareTo(Object c) method.

import java.util.PriorityQueue;

class Node implements Comparable{
public int a,b,c;
public void setA(int a) {
this.a = a;
}
public void setB(int b) {
this.b = b;
}
public void setC(int c) {
this.c = c;
}
public int compareTo(Node o) {
return new Integer(this.c).compareTo(o.c);
};
}

public class PQExample {
public static void main(String[] args) {
Node n = new Node();
n.setA(1);
n.setC(4);
Node n2 = new Node();
n2.setA(2);
n2.setC(6);
Node n3 = new Node();
n3.setA(3);
n3.setC(1);
PriorityQueue temp = new PriorityQueue();
temp.add(n); temp.add(n2);temp.add(n3);
while (!temp.isEmpty()) {
System.out.println(temp.poll().a);
}
}

}

Output

3
1
2

I learnt these concepts from Pratik Tandel (pt1989) ,  http://problemclassifier.appspot.com/
  • Проголосовать: нравится
  • -4
  • Проголосовать: не нравится

14 лет назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится
compareTo method is going to be slow, if you have many objects in PriorityQueue, because this method creates two objects, every time it is used. You may try to do it faster, if you compare int's yourself. 
Plus PriorityQueue can store objects, even if they don't implement Comparable interface, but here PriorityQueue should be created using the constructor that takes the object of the class, which implements Comparator interface.