树集示例 [英] TreeSet example

查看:31
本文介绍了树集示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第三个对象不在这里添加到树集中,尽管它是一个不同的对象?

Why the 3rd object is not being added to the treeset here though it is a different one?

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:

Your comparator function only uses fn:

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

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

TreeSet only uses ordering comparisons - it doesn't use hashCode() and equals().

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

By this comparison, st1 and st3 are equal (s1.compareTo(s3) will return 0) therefore st3 isn't added to the set.

如果你想保持区别,你应该比较 fn 然后如果 fn 值相同,则使用 ln:

If you want to maintain the distinction, you should probably compare fn and then use ln if the fn values are the same:

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

这篇关于树集示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆