mq007 mq007 - 1 year ago 139
C++ Question

Priority queue comparing - java vs c++

I have no idea how to use priority queue in java just like in C++.
In c++ we can make it like this:

priority_queue<object*, vector<object*>, compareClass>

So when we have class like this:

class Foo{
int number1;
int number2

We can use two different queues to compare in them by 2 different ideas just by making two compareClasses.

In java I got problem cause when I make queue like this:

PriorityQueue<Foo> pq = new PriorityQueue<Foo>();

I can override compareTo function just once.
I know that I can make override something like this:

class Foo implements Comparable<Foo>{
public int number1;
public int number2;

public int compareTo(Foo other){
if(number2 != // something)
return, other.number);
return, other.number2);

In this case complicity of program is different.
Can I make something like in C++ in Java?

Rob Rob
Answer Source

When you create your Java PriorityQueue, use the constructor that takes a Comparator. This allows you to use whatever comparison logic you want, despite any compareTo method that may already be defined for the class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download