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

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

TreeSet myclassSet = new TreeSet(myclassList);

I d

3条回答
  •  情话喂你
    2020-12-17 18:26

    If you just want the set to remove duplicates, used a HashSet, although that will shuffle the order of the objects returned by the Iterator in ways that appear random.
    But if you want to preserve the order somewhat, use LinkedHashSet, that will at least preserve the insertion order of the list.

    TreeSet is only appropriate if you need the Set sorted, either by the Object's implementation of Comparable or by a custom Comparator passed to the TreeSet's constructor.

提交回复
热议问题