当compareto返回0时理解TreeSet

2023-11-22

我创建了一个这样的学生课程:

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 & equals方法。所以我期待的是TreeSet将容纳所有 4 个物体,但我还可以看到它包含 3 个物体。你能解释一下原因吗new Student("A1","B2")不是我的一部分TreeSet?

还根据TreeSet 的 Java 文档在这里,它说:

如果指定元素尚不存在,则将其添加到该集合中。 更正式地说,如果集合 不包含满足 (e==null ? e2==null : e.equals(e2)) 的元素 e2。 如果该集合已包含该元素,则调用将离开该集合 不变并返回 false。

由于我没有覆盖equals方法那么为什么集合没有全部四个元素呢?


As java.util.TreeSet says:

TreeSet 实例使用其compareTo(或compare)方法执行所有元素比较,因此从集合的角度来看,此方法认为相等的两个元素是相等的

感谢@乔恩斯基特.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当compareto返回0时理解TreeSet 的相关文章

随机推荐