java - 树集示例

标签 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);
    }


}

 }

输出:

true
true
false
Girish J
Master M

最佳答案

您的比较器函数仅使用fn:

public int compareTo(Student o) {
    return this.fn.compareTo(o.fn);
}

TreeSet 使用排序比较 - 它不使用 hashCode()equals()

通过比较,st1st3 相等(s1.compareTo(s3) 将返回 0),因此 st3 未添加到集合中。

如果您想保持区别,您可能应该比较 fn,然后在 fn 值相同时使用 ln:

public int compareTo(Student o) {
    int fnResult = this.fn.compareTo(o.fn);
    return fnResult == 0 ? ln.compareTo(o.ln) : fnResult;
}

关于java - 树集示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11082197/

相关文章:

java - AspectJ:如何将方面库编织到 Java 项目中

java - Spring Boot应用程序中的循环 View 路径异常

java - 如何避免相机在四元数旋转时翻转?

java - 测试字符串是否是字符串列表中任何字符串的子字符串的有效方法

javascript - JQuery 表排序器不适用于日期范围字符串

java - 受jvm/jvm-options意外影响的代码示例

objective-c - 比较不同长度的字符串与 compare :options:range: produces wrong result

java - TreeSet 迭代的时间复杂度是多少?

java - 按 HashMap 中的值对对象进行排序

java - java集合框架中的比较器