问题
In a method I receive a generic object E extends Comparable<E>
as an argument. Now i want to create two priority queues.One which uses the comparator
used by E and other queue which uses the opposite of comparator
used by E(i.e. if E uses '<' then second queue must use '>=').
Please hep me how to create two such queues.
queue2=new PriorityQueue<E>(0,Collections.reverseOrder(e));
I am getting the error that reverseOrder
is not applicable.
please help
回答1:
Look at Collections.reverseOrder.
回答2:
Your object E
extends java.lang.Comparable,
but it is not a java.util.Comparator
.
Create your first queue w/o a Comparator and you'll get the ordering in your compareTo
function, then create a java.util.Comparator
that does the comparison in reverse (just call a.compareTo(b) and then negate the result) and create your second queue with that comparator.
回答3:
The single argument of Collections.reverseOrder is a Comparator and not a Collection. For your code simply use reverseOrder without an argument. You have to use a non-zero inital size, too. The following code will work.
queue2=new PriorityQueue<E>(1, Collections.reverseOrder());
回答4:
Below Program depicts how to do it.
I have StringLengthComparator
which compares based on string length. Using Collections.reverseOrder
I have created queue which is reverse ordered and another queue which is ordered correctly.
import java.util.Collections;
import java.util.Comparator;
import java.util.PriorityQueue;
public class TestReverseorder {
public static void main(String[] args) {
Comparator<String> comparator = new TestReverseorder().new StringLengthComparator();
PriorityQueue<String> reverse = new PriorityQueue<String>(10,
Collections.reverseOrder(comparator));
PriorityQueue<String> queue = new PriorityQueue<String>(10,comparator);
queue.add("1");
queue.add("12");
queue.add("123");
reverse.add("1");
reverse.add("12");
reverse.add("123");
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
while (!reverse.isEmpty()) {
System.out.println(reverse.poll());
}
}
public class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String x, String y) {
// Assume neither string is null. Real code should
// probably be more robust
if (x.length() < y.length()) {
return -1;
}
if (x.length() > y.length()) {
return 1;
}
return 0;
}
}
}
It will print output
Normal Order:
1
12
123
Reverse Order:
123
12
1
来源:https://stackoverflow.com/questions/12345451/how-to-get-inverse-of-a-comparator-in-java