2 回答

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
這里有幾個(gè)問(wèn)題需要解決:
您的比較運(yùn)算符不正確 - 它不是比較名稱(chēng)
你的comparator必須和equals一致才能實(shí)現(xiàn)set操作(詳見(jiàn)文檔
TreeSet
)
我建議您使用Comparator
靜態(tài)方法來(lái)構(gòu)建您的比較而不是實(shí)現(xiàn)您自己的compareTo
. 它更安全,更清晰:
Comparator<Student> nameOrder = Comparator.comparing(Student::getStudentName); Set<Student> students = new TreeSet<>(nameOrder.reverse());

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
我比較了 o1 和 o2 上的 getName() 方法,更正了排序。比較類(lèi)應(yīng)該是:
class StudentNameComparator implements Comparator<Student> {
? ? @Override
? ? public int compare(Student o1, Student o2) {
? ? ? ? return o1.getStudentName().compareTo(o2.getStudentName())*-1; //reverse ordering
? ? }
}
添加回答
舉報(bào)