您的位置:首页 > 编程语言 > Java开发

Java equals() and hashCode() Contract

2013-10-22 15:56 477 查看
http://www.programcreek.com/2011/07/java-equals-and-hashcode-contract/
TheJavasuperclassjava.lang.Objecthastwoveryimportantmethodsdefined:
public
boolean
equals(Objectobj)

public
int
hashCode()

Theyhavebeenprovedtobeveryimportantespeciallywhenuser-definedobjectsareaddedtoMaps.However,evenadvanced-leveldeveloperssometimescan’tfigureouthowtheyshouldbeused
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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: