Pourquoi ne TreeSet jeter un ClassCastException?

Je suis en train d'ajouter deux "Employés" des objets à un TreeSet:

Set<Employee> s = new TreeSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));

Mais il jette un ClassCastException:

Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to java.lang.Comparable
    at java.util.TreeMap.put(TreeMap.java:542)
    at java.util.TreeSet.add(TreeSet.java:238)
    at MyClient.main(MyClient.java:9)

Mais si j'ajoute un seul objet à la TreeSet:

Set<Employee> s = new TreeSet<Employee>();
s.add(new Employee(1001));

Ou si j'utilise un HashSet à la place:

Set<Employee> s = new HashSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));

Alors c'est réussi. Pourquoi l'exception arriver et comment puis-je résoudre ce problème?

  • Vous avez besoin de faire confiance que le message d'erreur est correct. Employee cannot be cast to java.lang.Comparable est le problème. Lorsque vous avez un élément, il n'est rien à comparer de sorte qu'il ne détecte pas le problème. HashSet n'utilise pas Comparables, de sorte qu'il ne vérifie pas non plus.
InformationsquelleAutor Rais Alam | 2013-04-11