Sie sind auf Seite 1von 3

TheGangofFive

Injavadatatypessplitbetweenprimitivesandcomplextypes,composedofprimitives,called
objects.[arethesetheonlydatatypes?]Objectcoupledatawithmethodsthatmanipulatethe
data.ThereisaspecialObjectclassthateveryjavaclassoutthereextends(evenifyoudidnt
explicitlyspecifiedso!).
Asaparentclass,Objectspecifiesdefault(inherited)implementationofcoupleofmethodsto
allitschildren.Therearefiveofthese(Objectclasshasalotmore,butonlyfiveofthemare
notmarkedasfinal):hashCode,equals,clone,finalizeandtoString

Notethatfivemethodsdescribedtherearenoordinarymethods,andmustbeimplementedin
aparticularway(exceptfromtoString).

1Equals

Objectshaveidentity,thatislocationinmemory,andstate,thatisobjectsdata.Bydefaultwe
cancompareanytypeofobjectintwowayseitherby==operator,orbyequalsmethod.The
equalsoperatoralwayscomparesonlyobjectslocationinmemoryinotherwords,itcanonly
tellusiftwocomparedvariablespointatthesameobjectinstanceinmemory.[2]Default
implementationofequalsmethoddoesjustthesame[1].Inordertomakeequalsmethod
compareobjectsdata,weneedtooverrideequalsmethod.Overridingthismethodmustbe
donebearinginmindtheserules:

(1)Equalsmethodmustdefineequalityrelation[3].Itmustbe
*reflexive
a.equals(a)
*symmetric
ifa.equals(b)thenb.equals(a)
*transitive
ifa.equals(b)andb.equals(c)thena.equals(c)

(2)Everyobjectisunequaltonull,thatis:
a.equals(null)==false

(3)Equalsmethodshouldbeconsistent,thatistoalwaysreturnthesameresultwhen
comparingthesameobjects
a.equals(b)==a.equals(b)

Thisbeingsaid,letsgetseehowaparticularimplementationmaylooklike.Getting1.1,2or3
wrongwithouttryingisrathernotlikelytohappen.Therealtrickabouttherestisproperly
comparinggivenfields.Doingitinwithoutanyadditionallibrariesiseasy,butitrequiresyou
tobecarefulandmaybeasourceofsubtlebugsinyourcode.Ifyoureallywanttodothator
youarejustcuriousmakesureyoucheckoutthis[A].

Herewearegoingtouseexternallibraries,fromApacheproject,specifically,EqualsBuilder.
Beadvicedthat
itsimplycomparesreferencetypesforequalityratherthandivingdeeperinto
them.

publicbooleanequals(Objectobj){
if(obj==null){returnfalse}
if(obj==this){returntrue}
if(obj.getClass()!=getClass()){
returnfalse
}
MyClassrhs=(MyClass)obj
returnnewEqualsBuilder()
.appendSuper(super.equals(obj))
.append(field1,rhs.field1)
.append(field2,rhs.field2)
.append(field3,rhs.field3)
.isEquals()
}

Ifyouwantdeepequalsutilityforcreatingyoutownmethodyougotfewotheroptions.Ifyou
areworkingusingJDK7,tryObjects.deepEquals[B],ifyouareonalowerversion,trythe
samemethodfromgoogleGuavalibrary[C]itsNPEproof,socomparisonofnullfieldsis
possiblewithnorisk.OtherlibraryworthcheckingisUnitils[D]

(1)Itbehavesspecifficalyfornullparameterandcoupleofotherthings,dontknowifitisworth
mentioning
(2)Thingsaredifferentforprimitves[astheyarealwaysdistinct,eachprimitiveiscreatedan
hasonlyonevariablepointingtoit?][howarethethingsfordifferenttypes(arraysetc)]
(3)

Notes
Whenisimplementingequalsmethodnecessary?
Whatarebasejavatypes?

References
[A]
http://www.javapractices.com/topic/TopicAction.do?Id=17
[B]
http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#deepEquals(java.lang.Objec
t,java.lang.Object)
[C]
http://docs.guavalibraries.googlecode.com/githistory/release/javadoc/com/google/commo
n/base/Objects.html#equal(java.lang.Object,java.lang.Object)
[D]
http://www.unitils.org/summary.html

Furtherreadingonequalsmethod:
http://www.artima.com/lejava/articles/equality.html
http://www.billthelizard.com/2008/08/implementingequalsinjava.html

2.HashCode

http://en.wikipedia.org/wiki/Java_hashCode()

Das könnte Ihnen auch gefallen