lea*_*ner 3 java compareto sortedset treeset
我创建了一个这样的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
+ "]";
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试类,我只是在我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
根据我的程序,输出是:
[Student [firstName=A1, lastName=A2], Student [firstName=A2, lastName=B2], Student [firstName=B1, lastName=B2]]
Run Code Online (Sandbox Code Playgroud)
在我的测试类中,我正在添加Student对象TreeSet,并且我还没有覆盖hashCode&equals方法.所以我期待TreeSet它将保存所有4个对象,但我也可以看到它包含3个对象.你能解释一下为什么new Student("A1","B2")不属于我的一部分TreeSet吗?
如果指定的元素尚不存在,则将其添加到此集合中.更正式地,如果集合不包含元素e2,则将指定的元素e添加到该集合中(e == null?e2 == null:e.equals(e2)).如果此set已包含该元素,则调用将保持set不变并返回false.
由于我没有覆盖该equals方法,为什么该集合没有所有四个元素?
mes*_*azs 11
正如java.util.TreeSet所说:
TreeSet实例使用compareTo(或compare)方法执行所有元素比较,因此从集合的角度来看,这个方法认为相等的两个元素是相等的
荣誉对@乔恩飞碟双向.