Why does TreeSet throw a ClassCastException?

前端 未结 6 823
遥遥无期
遥遥无期 2020-11-29 06:30

I am trying to add two \'Employee\' objects to a TreeSet:

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


        
6条回答
  •  我在风中等你
    2020-11-29 07:14

    TreeSet requires elements to implement the Comparable interface if a custom Comparator is not set. HashSet uses the equals/hashCode contract instead.

    You can add only one element into TreeSet which does not implement Comparable because it does not need to be compared with other elements.

    Take a look at the TreeMap.put(K key, V value) source code and you'll clearly see the reasons behind all your questions (TreeSet is based on TreeMap, hence the source reference).

提交回复
热议问题