Understanding TreeSet when compareto returns 0

后端 未结 5 802
逝去的感伤
逝去的感伤 2021-01-06 02:30

I have created a Student class like this:

public class Student implements Comparable {

    private String firstName;
    private String lastN         


        
5条回答
  •  Happy的楠姐
    2021-01-06 03:01

    Since you have compared only first name in compareTo method, you need

     @Override
    public int compareTo(Student student) {
        int comp = this.firstName.compareTo(student.firstName);
        if(comp==0) return this.lastName.compareTo(student.lastName);
        return comp;
    }
    

    when compareTo returns 0, treeSet assumes that its duplicate.

提交回复
热议问题