Java Reference
In-Depth Information
ownshallowcopyingofnonreferencefields),itisn'tnecessaryfortheclasscontaining
theoverriding clone() methodtoimplement Cloneable ,butitshouldimplement
this interface for consistency. String does not override clone() , so String ob-
jects cannot be deeply cloned.
Equality
The == and != operatorscomparetwoprimitivevalues(suchasintegers)forequality
( == ) or inequality ( != ). These operators also compare two references to see whether
theyrefertothesameobjectornot.Thislattercomparisonisknownasan identity check .
You cannot use == and != to determine whether two objects are logically the same
(ornot).Forexample,two Truck objectswiththesamefieldvaluesarelogicallyequi-
valent. However, == reports them as unequal because of their different references.
Note Because == and != perform the fastest possible comparisons, and because
stringcomparisonsneedtobeperformedquickly(especiallywhensortingahugenum-
berofstrings),the String classcontainsspecialsupportthatallowsliteralstringsand
string-valuedconstantexpressionstobecomparedvia == and != .(Iwilldiscussthis
supportwhenIpresent String in Chapter4 .)Thefollowingstatementsdemonstrate
these comparisons:
System.out.println("abc" == "abc"); // Output: true
System.out.println("abc" == "a"+"bc"); // Output: true
System.out.println("abc" == "Abc"); // Output: false
System.out.println("abc" != "def"); // Output: true
System.out.println("abc" == new String("abc")); // Output:
false
Recognizing the need to support logical equality in addition to reference equality,
Java provides an equals() method in the Object class. Because this method de-
faultstocomparingreferences,youneedtooverride equals() tocompareobjectcon-
tents.
Beforeoverriding equals() ,makesurethatthisisnecessary.Forexample,Java's
java.lang.StringBuffer class (discussed in Chapter 4 ) does not override
equals() .Perhapsthisclass'sdesignersdidnotthinkitnecessarytodetermineiftwo
StringBuffer objects are logically equivalent.
Search WWH ::




Custom Search