Collection: le tri d'une PriorityQueue par un Comparator
Bonjour,
Je cherche à comprendre le fonctionnement de PriorityQueue:
je ne comprends le fait qu'elle soit 'sorted' par ordre naturel:
Code:
1 2 3 4 5 6
| PriorityQueue<String> pq = new PriorityQueue<String>();
pq.add("e");
pq.add("a");
pq.offer("z");
System.out.println(pq);
==>[a, e, z] |
MAIS,supposant que je construise une collection d'objets T:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class T implements Comparator<T>{
int index;String nom;
public static void main(String[] args) {
PriorityQueue<T> pq = new PriorityQueue<T>();
T p1=new T();
p1.index=1;p1.nom="un";
Tp2=new T();
p2.index=1;p2.nom="deux";
Tp3=new T();
p3.index=3;p3.nom="trois";
pq2.add(p3);
pq2.add(p2);
pq2.add(p1);
System.out.println(pq2);
}
@Override
public int compare(To1, To2) {
return (o1.index > o2.index)? -1:1;
}
} |
Je dois normalement trier selon l'ordre inverse des index
Mais à l’exécution, j'ai une exception:
Citation:
Exception in thread "main" java.lang.ClassCastException: collection.T cannot be cast to java.lang.Comparable
Quelqu'un a une idée ,svp
Cordialement