Java equals() and hashCode() Contract

 

http://www.programcreek.com/2011/07/java-equals-and-hashcode-contract/

The Java super classjava.lang.Object has two very important methods defined:

public boolean equals(Object obj)

public int hashCode()

 

They have been provedto be very important especially when user-defined objects are added to Maps.However, even advanced-level developers sometimes can’t figure out how theyshould be used properly. In this tutorial, I will first show an example of howto use it and then explain how equals() and hashCode contract works.

1. A common mistake

Common mistake isshown in the example below.

 

import java.util.HashMap;
 
public class Apple {
	private String color;
 
	public Apple(String color) {
		this.color = color;
	}
 
	public boolean equals(Object obj) {
		if (!(obj instanceof Apple))
			return false;	
		if (obj == this)
			return true;
		return this.color == ((Apple) obj).color;
	}
 
	public static void main(String[] args) {
		Apple a1 = new Apple("green");
		Apple a2 = new Apple("red");
 
		//hashMap stores apple type and its quantity
		HashMap<Apple, Integer> m = new HashMap<Apple, Integer>();
		m.put(a1, 10);
		m.put(a2, 20);
		System.out.println(m.get(new Apple("green")));
	}
}


 

In this example, a green apple object is stored successfully in a hashMap, but when the map is asked to retrieve this object, the apple object is not found. The program above prints null. However, we can be sure that the object is stored in the hashMap by inspection in the debugger(snapshot below).
 

2. Problem caused byhashCode()

The problem is causedby the un-overridden method “hashCode()”.

The contract betweenequals() and hasCode() is that: 1. If two objects are equal, then they must have the same hash code. 2. If two objects have the same hashcode, they may or may not be equal.

The idea behind a Mapis to be able to find an object faster than a linear search. Using hashed keysto locate objects is a two-step process. Internally the Map stores objects asan array of arrays. The index for the first array is the hashcode() value ofthe key. This locates the second array which is searched linearly by usingequals() to determine if the object is found.

hashCode() in defaultimplementation in Object class returns distinct integers for distinct objects.Therefore, in the example above, same objects have different hashCode.

Hash Code is like asequence of garages for storage, different stuff can be stored in differentgarages. It is more efficient if you organize stuff to different place insteadof the same garage. So it’s good to equally distribute the hashCode value.

So the solution is toadd hashCode method to class. Here I just use the color string’s length fordemonstration.

public int hashCode(){

        return this.color.length();   

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值