Java Reference
In-Depth Information
Assumethattheexample'sstatementsareappendedto Listing2-27 's main() meth-
od—the java.util. prefix, <Point, String> ,and <> havetodowithpackages
and generics, which I discuss in Chapter 3 .
After main() createsits Point objectsandcallsits System.out.println()
methods, it executes this example's statements, which perform the following tasks:
• The first statement instantiates HashMap , which is in the java.util pack-
age.
• Thesecondstatementcalls HashMap 's put() methodtostore Listing2-27 's
p1 object key and the "first point" value in the hashmap.
• Thethirdstatementretrievesthevalueofthehashmapentrywhose Point key
is logically equal to p1 via HashMap 's get() method.
• Thefourthstatementisequivalenttothethirdstatement,butreturnsthenullref-
erence instead of "first point" .
Although objects p1 and Point(10, 20) are logically equivalent, these objects
have different hash codes, resulting in each object referring to a different entry in the
hashmap. If an object is not stored (via put() ) in that entry, get() returns null.
Correctingthisproblemrequiresthat hashCode() beoverriddentoreturnthesame
integervalueforlogicallyequivalentobjects.I'llshowyouhowtoaccomplishthistask
when I discuss HashMap in Chapter 5 .
String Representation
The toString() method returns a string-based representation of the current object.
This representation defaults to the object's class name, followed by the @ symbol, fol-
lowed by a hexadecimal representation of the object's hash code.
Forexample,ifyouweretoexecute System.out.println(p1); tooutput List-
ing 2-27 ' s p1 object, you would see a line of output similar to Point@3e25a5 .
( System.out.println() calls p1 's inherited toString() method behind the
scenes.)
Youshouldstrivetooverride toString() sothatitreturnsaconcisebutmeaning-
fuldescriptionoftheobject.Forexample,youmightdeclare,in Listing2-27 's Point
class, a toString() method that is similar to the following:
@Override
public String toString()
{
Search WWH ::




Custom Search