Java Reference
In-Depth Information
Followingthecast,thecontract'sreflexivity,symmetry,andtransitivityrequirements
are met by only allowing Point s to be compared with other Point s, via expression
p.x == x && p.y == y .
Thefinalcontractrequirement,consistency,ismetbymakingsurethatthe equals()
methodisdeterministic.Inotherwords,thismethoddoesnotrelyonanyfieldvaluethat
could change from method call to method call.
Tip Youcanoptimizetheperformanceofatime-consuming equals() methodby
firstusing == todetermineif o 'sreferenceidentifiesthecurrentobject.Simplyspecify
if (o == this) return true; asthe equals() method'sfirststatement.
Thisoptimizationisnotnecessaryin Listing2-27 ' s equals() method,whichhassat-
isfactory performance.
It is important to always override the hashCode() method when overriding
equals() . I did not do so in Listing 2-27 because I have yet to formally introduce
hashCode() .
Finalization
Finalization refers to cleanup via the finalize() method, which is known as a fi-
nalizer .The finalize() method'sJavadocumentation states that finalize() is
“called by the garbage collector on an object when garbage collection determines that
there are no more references to the object. A subclass overrides the finalize()
method to dispose of system resources or to perform other cleanup.”
Object 's version of finalize() does nothing; you must override this method
withanyneededcleanupcode.BecausetheJVMmightnevercall finalize() before
anapplicationterminates,youshouldprovideanexplicitcleanupmethod,andhave fi-
nalize() call this method as a safety net in case the method is not otherwise called.
Caution Never depend on finalize() for releasing limited resources such as
graphicscontextsorfiledescriptors.Forexample,ifanapplicationobjectopensfiles,
expectingthatits finalize() methodwillclosethem,theapplicationmightfindit-
self unable to open additional files when a tardy JVM is slow to call finalize() .
Whatmakesthisproblemworseisthat finalize() mightbecalledmorefrequently
onanotherJVM,resultinginthistoo-many-open-filesproblemnotrevealingitself.The
developer might thus falsely believe that the application behaves consistently across
different JVMs.
Search WWH ::




Custom Search