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{
public:
int number1;
int number2
Foo(){};
};
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;
@Override
public int compareTo(Foo other){
if(number2 != // something)
return Int.compare(number, other.number);
else
return Int.compare(number2, other.number2);
}
}
In this case complicity of program is different. Can I make something like in C++ in Java?
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.