一段代码告诉你,HashCode和Equals的关系

HashCode

表示对象的地址值,一般情况下,并不使用,但有些hash优化过程中,涉及较多,比如hashMap, 源码中用HashCode做散列标准

Equals

评判对象是否一致

如果重写Equals 却不重写hashCode 有什么问题呢?

package test;

import java.util.HashMap;

public class Test {
	public static void main(String args[]) {
		HashMap<Test1, String> map = new HashMap<>();
		String codeWithUPCase = "123ABCD";
		Test1 testWithUPCase = new Test1(codeWithUPCase);
		map.put(testWithUPCase, codeWithUPCase);
		
		String codeWithLowCase = "123abcd";
		Test1 testWithLowCase = new Test1(codeWithLowCase);
		map.put(testWithLowCase, codeWithLowCase);
		
		System.out.println(testWithUPCase.equals(testWithLowCase));
		System.out.println(map.get(testWithUPCase));

		System.out.println(map.get(testWithLowCase));

	}
	
}
class Test1 {
	private String code;
	
	
	@Override
	public String toString() {
		return "Test1 [code=" + code + "]";
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Test1 other = (Test1) obj;
		if (code == null) {
			if (other.code != null)
				return false;
		} else if (!code.equalsIgnoreCase(other.code))
			return false;
		return true;
	}

	public Test1() {
		super();
	}

	public Test1(String code) {
		super();
		this.code = code;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
}

结果
true
123ABCD
123abcd

显然不正确,至于原因呢?
第一 : 我设置的equals是忽略大小写比较,所以应该是相等的。
故第二次put应该会替换第一次的值。但显然结果未替换, 造成了问题。这一点在项目中很容易引发一系列问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值