Java Reference
In-Depth Information
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.
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
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.
(
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()
{