List to TreeSet conversion produces: “java.lang.ClassCastException: MyClass cannot be cast to java.lang.Comparable”

前端 未结 3 589
刺人心
刺人心 2020-12-17 18:19
List myclassList = (List) rs.get();

TreeSet myclassSet = new TreeSet(myclassList);

I d

3条回答
  •  半阙折子戏
    2020-12-17 18:33

    If you don't pass an explicit Comparator to a TreeSet, it will try to compare the objects (by assuming they are Comparable). And if they aren't Comparable, it cannot compare them, so this exception is thrown!
    TreeSets are sorted sets and require either objects to be Comparable or a Comparator to be passed in to determine how to sort the objects in the Set.

提交回复
热议问题