equals和hashCode方法分析

1.HashSet存放的是无序,不能重复的对象,当添加一个对象的时,它会先检查此对象的
hashCode值是否与集合中对象的hashCode值相等,如果不等,直接将对象加进去,如果相等,则再用equals方法判断,如果返回的是true表示集合中已经存在此对象,不再进行添加,若返回false将对象添加进去

2.简单来说,如果两个对象equals返回true则它们的hashCode值一定相等,如果返回false它们的hashCode不一定不同,因为equals判定的是否为同一个对象,当然这是针对未被重写来说

看下面例子


import java.util.HashSet;

public class SetTest {

public static void main(String[] args) {
HashSet set = new HashSet();
Student s1 = new Student("zhansan",20);
Student s2 = new Student("zhansan",20);
set.add(s1);
set.add(s2);
System.out.println(set);
}

}

class Student {
private String name = null;

private int age = 0;

public Student(String name, int age){
this.name = name;
this.age = age;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + age;
result = PRIME * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}




如果不对Student类重写equals方法和hashCode方法,当new两个内容相同的对象时,HashSet还是会添加进去,因为两对象的hashCode值不一样,如果像上面那样写了的话则是对内容进行判断,内容相同不再添加
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值