微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 比较时理解TreeSet返回0

我创建了一个这样的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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐