为什么重写HashCode()和equal()

先揭晓答案:重写这俩个方法是为了在使用HashMap 传入自定义Key时,HashMap还能根据需求正常使用。

现在有这样的需求:根据Key的属性返回value。

不重写会怎样,来看代码

class Key{
	int i;
	Key(int i){
		this.i=i;
	}
}
public class DefineKey {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Key key1=new Key(1);
		Key key2=new Key(1);
		HashMap<Key,Integer> map=new HashMap<>();
		map.put(key1, 1);
		System.out.println(map.get(key2));
	}
}

//执行结果  为  null

那么只重写HashCode()呢?

import java.util.HashMap;
class Key{
	Integer i;
	Key(int i){
		this.i=i;
	}
	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return i.hashCode();
	}
}
public class DefineKey {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Key key1=new Key(1);
		Key key2=new Key(1);
		HashMap<Key,Integer> map=new HashMap<>();
		map.put(key1, 1);
		System.out.println(map.get(key2));
	}
}
//  还是null, 虽然 get(key2) 找到了 key1所在桶 但父类的equal方法对于俩个对象还是不等的

重写俩个方法呢??

class Key{
	Integer i;
	Key(int i){
		this.i=i;
	}
	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return i.hashCode();
	}
	@Override
	public boolean equals(Object obj) {
		// TODO Auto-generated method stub
		Key key=(Key)obj;
		return this.i==key.i;
	}
}
public class DefineKey {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Key key1=new Key(1);
		Key key2=new Key(1);
		HashMap<Key,Integer> map=new HashMap<>();
		map.put(key1, 1);
		System.out.println(map.get(key2));
	}
}

这样的话 就返回 1 了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值