hashmap的equals方法_文件hash什么用「建议收藏」

hashmap的equals方法_文件hash什么用「建议收藏」http://www.programcreek.com/2011/07/java-equals-and-hashcode-contract/TheJavasuperclassjava.lang.Objecthastwoveryimportantmethodsdefined:publicbooleanequals(Objectobj)publi

hashmap的equals方法_文件hash什么用「建议收藏」"

 

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

}

 

今天的文章hashmap的equals方法_文件hash什么用「建议收藏」分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/57923.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注