Java Reference
In-Depth Information
Multiple Objects
In the previous section, you saw how to manipulate a single array object. In this section,
we will delve deeper into the implications of reference semantics by considering what
happens when there are multiple objects and multiple references to the same object.
Consider the following code:
int[] list1 = new int[5];
int[] list2 = new int[5];
for (int i = 0; i < list1.length; i++) {
list1[i] = 2 * i + 1;
list2[i] = 2 * i + 1;
}
int[] list3 = list2;
Each call on new constructs a new object and this code has two calls on new ,so
that means we have two different objects. The code is written in such a way that
list2 will always have the exact same length and sequence of values as list1 .
After the two arrays are initialized, we define a third array variable that is assigned to
list2 . This step creates a new reference but not a new object. After the computer
executes the code, memory would look like this:
[0]
[1]
[2]
[3]
[4]
list1
1
3
5
7
9
[0]
[1]
[2]
[3]
[4]
list2
1
3
5
7
9
list3
We have three variables but only two objects. The variables list2 and list3 both
refer to the same array object. Using the cell phone analogy, you can think of this as
two people who both have the cell phone number for the same person. That means
that either one of them can call the person. Or, as another analogy, suppose that both
you and a friend of yours know how to access your bank information online. That
means that you both have access to the same account and that either one of you can
make changes to the account.
The implication of this method is that list2 and list3 are in some sense both
equally able to modify the array to which they refer. The line of code
list2[2]++;
will have exactly the same effect as the line
list3[2]++;
 
 
Search WWH ::




Custom Search