Gir*_*ish 2 java string-comparison treeset
为什么第三个对象没有被添加到树集中,虽然它是一个不同的?
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
true
true
false
Girish J
Master M
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 11
您的比较器功能仅使用fn:
public int compareTo(Student o) {
return this.fn.compareTo(o.fn);
}
Run Code Online (Sandbox Code Playgroud)
TreeSet 仅使用排序比较 - 它不使用hashCode()和equals().
通过这种比较,st1并且st3相等(s1.compareTo(s3)将返回0)因此st3不会被添加到集合中.
如果你想保持区别,你应该比较fn然后使用,ln如果fn值是相同的:
public int compareTo(Student o) {
int fnResult = this.fn.compareTo(o.fn);
return fnResult == 0 ? ln.compareTo(o.ln) : fnResult;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22706 次 |
| 最近记录: |