hashCode()与equals()

本文围绕hashCode()方法和HashSet展开。介绍了HashSet采用哈希算法存取对象,通过对象的HashCode判断唯一性。解析了覆盖hashCode()方法对HashSet存储结果的影响,还指出改变对象属性致哈希码改变会造成内存泄露,强调类实例在equals()相等时哈希码也应相等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

hashCode()作用

按照先例,先上段代码:

public class Person {
	public String name;
	public int age;
	
	public Person(String n, int a){
		this.name = n;
		this.age = a;
	}
}

Collection collection = new ArrayList<>();
		collection.add(new Person("111",1));
		collection.add(new Person("222",2));
		collection.add(new Person("333",3));
		collection.add(new Person("111",1));
		
		System.out.println(collection.size());

结果为4,然后我们把ArrayList改为HashSet,结果还是为4。
接着,我们覆盖Person类中的hashCode().

public class Person {
	public String name;
	public int age;
	
	public Person(String n, int a){
		this.name = n;
		this.age = a;
	}

	@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;
		Person other = (Person) 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;
	}
	
	
}


Collection collection = new HashSet<>();
        collection.add(new Person("111",1));
        collection.add(new Person("222",2));
        collection.add(new Person("333",3));
        collection.add(new Person("111",1));
        
        System.out.println(collection.size());

结果竟然神奇地变为3。
出现这一结果的原因就在于 Person中的hashCode()方法。
在搞清楚这个原因之前,我们还是先了解下HashSet的工作原理

HashSet

HashSet是采用哈希算法存取对象的集合,它内部采用对某个数字n进行取余的方式对哈希码进行分组和划分对象的存储区域。Object类中定义了一个hashCode()方法来返回每个java对象的哈希码,然后根据哈希码找到对应的存储区域,最后取出该存储区域内的每个元素与该对象进行 equals方法比较,这样不用遍历集合中的所有元素。因此,HashSet集合具有很好的对象检索性能,但同时,它存储对象的效率要低些,因为在添加对象时,要先算出对象的哈希码和根据这个哈希码来确定对象在集合中的存放位置。

原因解析

通过以上描述,我们知道了HashSet不同于ArrayList,它是通过存入对象的HashCode来判断对象的唯一性,如果哈希码相等的两个对象,在HashSet中仅存一份。
需要注意的是,如果我们没有覆盖Person中的hashCode(),那么HashSet就会默认通过Person的超类Object中的hashCode()方法来算出哈希码,Object中的hashCode()又是通过对象在内存中的地址来判断的,因此new Person(“111”,1)跟new Person(“111”,1)算出的哈希码是不同的。只有覆盖了hashCode(),这两者的哈希值才会相同,因为覆盖后的hashCode()是通过 name跟age字段来确定的。

内存泄露风险

Collection collection = new HashSet<>();
		
		Person p1 = new Person("111",1);
		Person p2 = new Person("222",2);
		Person p3 = new Person("333",3);
		Person p4 = new Person("111",1);
		collection.add(p1);
		collection.add(p2);
		collection.add(p3);
		collection.add(p4);
		
		collection.remove(p1);

结果与预期的一样为2,p1被成功的移除了。
但改写一下:

Collection collection = new HashSet<>();
		
		Person p1 = new Person("111",1);
		Person p2 = new Person("222",2);
		Person p3 = new Person("333",3);
		Person p4 = new Person("111",1);
		collection.add(p1);
		collection.add(p2);
		collection.add(p3);
		collection.add(p4);
		
		p1.name="aaa";
		collection.remove(p1);

结果却不是我们想的那样是2,而是3.说明p1没有成功移除,这又是为什么呢?因为我们改变了name的值,前面说过,Person的哈希码跟name和age有关,改变了name的值,哈希码自然也改变了,因此p1跟原来的p1在HashSet中并非同一份,这时就移除不了之前的p1了,造成了内存泄露。

注意事项

为了保证一个类的实力对象能在HashSet中正常存储,要求这个类的两个实力对象在equals()方法比较的结果相等时,他们的哈希码也必须相等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fastsy

打赏一份隆江猪脚饭吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值