下面的程序描述了如何做到这一点。
我有StringLengthComparator
基于字符串长度的比较。使用Collections.reverseOrder
我创建了反向排序的队列和另一个正确排序的队列。
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;
}
}
}
它将打印输出
Normal Order:
1
12
123
Reverse Order:
123
12
1