加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 比较时理解TreeSet返回0

发布时间:2020-12-15 04:46:22 所属栏目:Java 来源:网络整理
导读:我创建了一个这样的Student类: public class Student implements ComparableStudent { private String firstName; private String lastName; public Student(String firstName,String lastName) { this.firstName = firstName; this.lastName = lastName; }
我创建了一个这样的Student类:

public class Student implements Comparable<Student> {

    private String firstName;
    private String lastName;

    public Student(String firstName,String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    // Getters & Setters follow here...

    @Override
    public int compareTo(Student student) {
        int hash = this.firstName.compareTo(student.firstName);
        return hash;
    }

    @Override
    public String toString() {
        return "Student [firstName=" + firstName + ",lastName=" + lastName
                + "]";
    }

}

这是我的测试类,我只是在我的TreeSet中添加元素:

public class SortedSetExample1 {
    public static void main(String[] args) {
        SortedSet<Student> set = new TreeSet<Student>();
        set.add(new Student("A1","A2"));
        set.add(new Student("B1","B2"));
        set.add(new Student("A1","B2"));
        set.add(new Student("A2","B2"));
        System.out.println(set);
    }
}

根据我的程序,输出是:

[Student [firstName=A1,lastName=A2],Student [firstName=A2,lastName=B2],Student [firstName=B1,lastName=B2]]

在我的测试类中,我将Student对象添加到TreeSet,而且我还没有覆盖hashCode&等于方法.所以我期待TreeSet将保存所有4个对象,但我也可以看到它包含3个对象.你能解释为什么新学生(“A1”,“B2”)不属于我的TreeSet吗?

此外,根据Java docs for TreeSet,它说:

Adds the specified element to this set if it is not already present.
More formally,adds the specified element e to this set if the set
contains no element e2 such that (e==null ? e2==null : e.equals(e2)).
If this set already contains the element,the call leaves the set
unchanged and returns false.

因为我没有覆盖equals方法,那么为什么集合没有所有四个元素?

解决方法

正如 java.util.TreeSet所说:

a TreeSet instance performs all element comparisons using its compareTo (or compare) method,so two elements that are deemed equal by this method are,from the standpoint of the set,equal

感谢@Jon Skeet.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读