当compareto返回0时了解TreeSet [英] Understanding TreeSet when compareto returns 0
问题描述
我创建了一个像这样的学生班:
I have created a Student class like this:
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中:
This is my test class where I just add elements to my 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);
}
}
根据我的程序,输出为:
As per my program the output is:
[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
吗?
In my test class I am adding Student
objects to TreeSet
, and also I have not overridden the hashCode
& equals
methods. So I was expecting that the TreeSet
will hold all the 4 objects but I can also see that it contains 3 objects. Can you please explain why new Student("A1","B2")
is not part of my TreeSet
?
也按照 TreeSet的Java文档在这里说:
将指定的元素添加到该集中(如果尚不存在). 更正式地说,将指定的元素e添加到该集合中(如果该集合存在的话) 不包含任何元素e2使得(e == null?e2 == null:e.equals(e2)). 如果此集合已经包含该元素,则调用将离开该集合 不变并返回false.
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
方法,那么为什么集合中没有全部四个元素呢?
As I have not overridden the equals
method then why the collection is not having all the four elements?
推荐答案
作为 java.util.TreeSet 说:
TreeSet实例使用其compareTo(或compare)方法执行所有元素比较,因此从该集合的角度来看,此方法认为相等的两个元素相等.
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 表示敬意.
这篇关于当compareto返回0时了解TreeSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!