Set集合类(注意)

来源:互联网 发布:sql sp4补丁安装失败 编辑:程序博客网 时间:2024/04/28 02:55

Customer类的equals()方法

public boolean equals(Object o)

{

    if(this == o) return true;

    if(!(o instanceof Custormer)) return false;

    final Custormer other = (Customer)o;

    if(this.name.equals(other.getName()) && this.age == other.getAge())

    return true;

else

   return false;

//向HashSet中加入两个Customer对象

Set set new HashSet();

Customer customer1 = new Customer("Jim",18);

Customer customer2 = new Customer("Jim",18);

set.add(customer1);

set.add(customer2);

Sysem.out.println(set.size());

//实际输出结果为2

由于customer1.equls(customer2)的比较结果为true,按理说HashSet粉应该把customer1加入集合中,但实际上以上程序的输出结果为2,表明集合中加入了两个对象.出现这一非正常现象的原因在于customer1和customer2的哈希码不一样,因此HashSet为customer1和customer2计算出不同的存放位置,于是把它们存放在集合中的不同地方.

为了保证HashSet正常工作,如果Customer类覆盖了equals()方法,也应该覆盖hashCode()方法,并且保证两个相等的Customer对象的哈希码也一样

pubic int hashCode()

{

   int resule;

result = (name == null? 0 : name.hashCode());

result = 29 * result + (age == null ? 0 : age.hashCode());

return result;

}

原创粉丝点击