Java equals() and hashCode() Contract

来源:互联网 发布:linux系统如何上网 编辑:程序博客网 时间:2024/06/13 02:52

 

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 quantityHashMap<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();   

}

 

原创粉丝点击