Java equals() and hashCode() Contract
2013-10-22 15:56
477 查看
TheJavasuperclassjava.lang.Objecthastwoveryimportantmethodsdefined:
public booleanequals(Objectobj) public inthashCode() |
properly.Inthistutorial,Iwillfirstshowanexampleofhowtouseitandthenexplainhowequals()andhashCodecontractworks.
1.Acommonmistake
Commonmistakeisshownintheexamplebelow.
importjava.util.HashMap; publicclassApple{ privateStringcolor; publicApple(Stringcolor){ this.color=color; } publicbooleanequals(Objectobj){ if(!(objinstanceofApple)) returnfalse; if(obj==this) returntrue; returnthis.color==((Apple)obj).color; } publicstaticvoidmain(String[]args){ Applea1=newApple("green"); Applea2=newApple("red"); //hashMapstoresappletypeanditsquantity HashMap<Apple,Integer>m=newHashMap<Apple,Integer>(); m.put(a1,10); m.put(a2,20); System.out.println(m.get(newApple("green"))); } }
Inthisexample,agreenappleobjectisstoredsuccessfullyinahashMap,butwhenthemapisaskedtoretrievethisobject,theappleobjectisnotfound.Theprogramaboveprintsnull.However,wecanbesurethattheobjectisstoredinthehashMapbyinspectioninthedebugger(snapshotbelow).
2.ProblemcausedbyhashCode()Theproblemiscausedbytheun-overriddenmethod“hashCode()”.Thecontractbetweenequals()andhasCode()isthat:
1.Iftwoobjectsareequal,thentheymusthavethesamehashcode.
2.Iftwoobjectshavethesamehashcode,theymayormaynotbeequal.TheideabehindaMapistobeabletofindanobjectfasterthanalinearsearch.Usinghashedkeystolocateobjectsisatwo-stepprocess.InternallytheMapstoresobjectsasanarrayofarrays.Theindexforthefirstarrayisthehashcode()valueofthekey.Thislocatesthesecondarraywhichissearchedlinearlybyusingequals()todetermineiftheobjectisfound.hashCode()indefaultimplementationinObjectclassreturnsdistinctintegersfordistinctobjects.Therefore,intheexampleabove,sameobjectshavedifferenthashCode.HashCodeislikeasequenceofgaragesforstorage,differentstuffcanbestoredindifferentgarages.Itismoreefficientifyouorganizestufftodifferentplaceinsteadofthesamegarage.Soit’sgoodtoequallydistributethehashCodevalue.SothesolutionistoaddhashCodemethodtoclass.HereIjustusethecolorstring’slengthfordemonstration.
publicint hashCode(){ returnthis.color.length(); } |
相关文章推荐
- Java equals() and hashCode() Contract[转]
- Java equals() and hashCode() Contract
- Equals and Hash Code in Java(Sun认证重点试题)
- How to implement equals() and hashCode() methods in Java[reproduced]
- Working with hashCode and equals methods in java
- Working with hashCode and equals methods in java
- equals and Hashcode method in Java
- override the hashcode and equals method in java
- Java compareTo, equals and hashcode
- JAVA 基础之 equals and HashCode
- HashCode and Equals method in Java object – A pragmatic concept
- java 中在Lab2_实验 中遇到的问题 关于equals hashcode 和==
- Effective Java 3rd 条目11 当你覆写equals时每次都覆写hashCode
- Effective Java 英文 第二版 读书笔记 Item 9:Always override hashCode when you override equals
- lombok @EqualsAndHashCode 注解的影响
- best strategies for implementation of equals() and hashcode() in your persistent classes
- @EqualsAndHashCode()注解详解
- lombok @EqualsAndHashCode 注解的影响
- Java object equals hashcode
- java中的 equals + hashCode