Java Reference
In-Depth Information
Thismethod'stwo(possiblynull)arguments,denotedby
e1
and
e2
below,aredeeply
equal when any of the following conditions hold:
•
e1
and
e2
are arrays of object reference types, and
Ar-
rays.deepEquals(e1, e2)
would return true
•
e1
and
e2
arearraysofthesameprimitivetype,andtheappropriateoverload-
ing of
Arrays.equals(e1, e2)
would return true.
•
e1 == e2
•
e1.equals(e2)
would return true.
Equalityimpliesdeepequality,buttheconverseisn'tnecessarilytrue.Inthefollowing
example,
x
and
y
are deeply equal but are not equal:
Object common = "string";
Object[] x = {"string"};
Object[] y = {"string"};
System.out.println("x == y: "+(x == y)); // false (two dif-
ferent references)
System.out.println("Objects.equals(x,
y):
"+Ob-
jects.equals(x, y)); // false
System.out.println("Objects.deepEquals(x,
y):
"+Ob-
jects.deepEquals(x, y)); // true
Arrays
x
and
y
arenotequalbecausetheycontaintwodifferentreferencesand
Ob-
jects.equals()
is using reference equality (comparing their references) in this
context. (Object equality, or comparing object contents, occurs when a class overrides
Object
's
equals()
method.)However,thesearraysaredeeplyequalbecause
x
and
y
arebotharraysofobjectreferencetypesand
Arrays.deepEquals(x, y)
would
return true.
Note
Unlikethe
java.lang.Object
class,whichisautomaticallyimportedbe-
causeofits
java.lang
prefix,youmustexplicitlyimport
Objects
intoyoursource
code(
import java.util.Objects;
)whenyouwanttoavoidhavingtospecify
the
java.util
prefix.
TheJavadocumentationforthe
requireNonNull()
methodsstatesthattheyare
designedprimarilyfordoingparametervalidationinmethodsandconstructors.Theidea
istocheckamethod'soraconstructor'sparametervaluesfornullreferencesbeforeat-
temptingtousethesereferenceslaterinthemethodorconstructor,andavoidpotential
NullPointerException
s.
Listing 6-10
provides a demonstration.