Java Reference
In-Depth Information
Since both variables refer to the same array object, you can access the array
through either one.
Reference semantics help us to understand why a simple == test does not give us
what we might expect. When this test is applied to objects, it determines whether two
references are the same (not whether the objects to which they refer are somehow
equivalent). In other words, when we test whether two references are equal, we are
testing whether they refer to exactly the same object.
The variables list2 and list3 both refer to the same array object. As a result, if
we ask whether list2 == list3 , the answer will be yes (the expression evaluates
to true ). But if we ask whether list1 == list2 , the answer will be no (the expres-
sion evaluates to false ) even though we think of the two arrays as somehow being
equivalent.
Sometimes you want to know whether two variables refer to exactly the same object,
and for those situations, the simple == comparison will be appropriate. But you'll also
want to know whether two objects are somehow equivalent in value, in which case you
should call methods like Arrays.equals or the string equals method.
Understanding reference semantics also allows you to understand why a method is
able to change the contents of an array that is passed to it as a parameter. Remember
that earlier in the chapter we considered the following method:
public static void incrementAll(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i]++;
}
}
We saw that when our variable list was initialized to an array of odd numbers,
we could increment all of the values in the array by means of the following line:
incrementAll(list);
When the method is called, we make a copy of the variable list . But the variable
list is not itself the array; rather, it stores a reference to the array. So, when we
make a copy of that reference, we end up with two references to the same object:
[0]
[1]
[2]
[3]
[4]
list
1
3
5
7
9
data
Search WWH ::




Custom Search