为什么第三个对象不在这里添加到树集中,尽管它是一个不同的对象?
import java.util.*;
class Student implements Comparable<Student>{
public String fn,ln;
public Student(String fn,String ln){
this.fn=fn;
this.ln=ln;
}
//overiding equals
public boolean equals(Object o) {
if (!(o instanceof Student))
return false;
Student s=(Student) o;
if(this==s)
return true;
if(this.fn.equals(s.fn) && this.ln.equals(s.ln))
return true;
return false;
}
//overiding hashcode
public int hashCode() {
return fn.hashCode()+ln.hashCode();
}
//overiding compareTo
public int compareTo(Student o) {
return this.fn.compareTo(o.fn);
}
}
public class Practice {
public static void main(String[] args) {
Student st1=new Student("Girish","J");
Student st2=new Student("Master","M");
Student st3=new Student("Girish","Jay");
Set S=new TreeSet();
//adding 3 different student objects
System.out.println(S.add(st1));
System.out.println(S.add(st2));
System.out.println(S.add(st3));
Iterator sitr=S.iterator();
while(sitr.hasNext())
{
Student stu=(Student) sitr.next();
System.out.println(stu.fn+" "+stu.ln);
}
}
}输出:
true
true
false
Girish J
Master M发布于 2012-06-18 11:55:47
您的比较器函数只使用fn
public int compareTo(Student o) {
return this.fn.compareTo(o.fn);
}TreeSet只使用排序比较-它不使用hashCode()和equals()。
通过这个比较,st1和st3是相等的(s1.compareTo(s3)将返回0),因此st3不会添加到集合中。
如果您想保持这种区别,您可能应该比较fn,然后如果fn值相同,则使用fn:
public int compareTo(Student o) {
int fnResult = this.fn.compareTo(o.fn);
return fnResult == 0 ? ln.compareTo(o.ln) : fnResult;
}发布于 2012-06-18 12:05:27
您的观察是正确的,TreeSet不使用.equals和.hashcode进行比较。
来自javadocs:
This is so because the Set interface is defined in terms of the equals operation, but 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. 基本上,他们是说对于TreeSet来说,平等不是通过.equals来确定的,而是通过类似接口上的.compareTo来确定的。注意,.compareTo应该始终与.equals保持一致,这意味着如果a.equals(b),那么a.compareTo(b) == 0。
这与TreeSet是SortedSet的实现这一事实有关。因此,它需要.compareTo来确定顺序,因为在这种情况下,.equals是不够的。
PS:如果您不希望实现可比较的(有时您无法实现,因为您可能并不总是控制objet的代码),您可以始终将一个比较器传递给TreeSet构造函数。
发布于 2012-06-18 11:57:04
您的比较只使用fn值..。
public int compareTo(Student o) {
return this.fn.compareTo(o.fn);
}对于第三个Student失败,因为第一个名称与第一个Student相同。
您需要调整代码以比较fn和ln值.
public int compareTo(Student o) {
int firstNameComparison = this.fn.compareTo(o.fn);
if (firstnameComparison != 0){
// the first names are different
return firstNameComparison;
}
else {
// the first names are the same, so compare the last name
return this.ln.compareTo(o.ln);
}
}此代码首先比较fn值。如果它们是相同的,则比较ln值。
https://stackoverflow.com/questions/11082197
复制相似问题