我创建了一个这样的学生课程:
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
方法那么为什么集合没有全部四个元素呢?