Sotto il programma viene illustrato come eseguirlo.
Ho StringLengthComparator
che si confronta in base alla lunghezza della stringa. Utilizzo di Collections.reverseOrder
Ho creato una coda ordinata inversa e un'altra coda ordinata correttamente.
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;
}
}
}
Si stamperà uscita
Normal Order:
1
12
123
Reverse Order:
123
12
1
fonte
2012-09-10 05:59:56
queue2 = new PriorityQueue (0, Collections.reverseOrder (e)); –
Ho ricevuto l'errore che l'ordine inverso non è applicabile. per favore aiuto –
I * mai * sapeva che 'Collections.reverseOrder' era lì. Grazie! –