线程“ main”中的异常java.lang.ClassCastException: setcollection.Enseignant无法转换为java.lang.Comparable
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Enseignant e=new Enseignant();
Enseignant e1=new Enseignant(1,"bargaoui","haythem");
Enseignant e2=new Enseignant(12,"islem","ben ahmed");
System.out.println(e1.toString());
System.out.println(e2.toString());
System.out.println(e1.equals(e2));
TreeSet<Enseignant> treeset = new TreeSet<Enseignant>();
Enseignant E1=new Enseignant(1,"mohamed","ben brahim");
Enseignant E2=new Enseignant(2,"imed","rouabi");
Enseignant E3=new Enseignant(3,"salim","ali");
Enseignant E4=new Enseignant(4,"zayneb","sassi");
Enseignant E5=new Enseignant(5,"khalid","louati");
Enseignant E6=new Enseignant(6,"hatem"," himadi");
treeset.add(E1);
treeset.add(E2);
treeset.add(E3);
treeset.add(E4);
treeset.add(E5);
treeset.add(E6);
System.out.println(treeset.contains(E4));
System.out.println(treeset.contains(E1.getId()));
System.out.println(treeset.remove(E6));
Iterator iterator = treeset.iterator();
// afficher tous les éléments de TreeSet
System.out.println("éléments de TreeSet");
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
线程“ main”中的异常java.lang.ClassCastException:
答案 0 :(得分:2)
由于您使用的是TreeSet,将进行一些比较,并且需要Comparator <>。
您可以做两件事。
public class Enseignant implements Comparable<Enseignant> {
...
public int compareTo(Enseignant other) {
// Compare here
return 0;
}
...
}
TreeSet<Enseignant> treeset = new TreeSet<>(new Comparator<Enseignant>(){
public int compare(Enseignant e1, Enseignant e2) {
// Compare here.
return 0;
}
});