Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^492) | One-Dimensional Arrays
int[] numbers = {2, 4, 6, 9};
int[] sameNumbers = new int[numbers.length];
// Deep copy of numbers to someNumbers
for (int index = 0; index < numbers.length; index++)
sameNumbers[index] = numbers[index];
// Compare arrays component by component
booleancompareArrays(int[] one, int[] two)
{
if (one.length != two.length)
return false;
booleanresult = true;
int index = 0;
while(index < one.length && result)
{
if (one[index] == two[index])
index++;
else
result = false;
}
returnresult;
}
a. Result is false; these are two different arrays.
b. Result is true after a shallow copy.
numbers[ 0 ]
numbers[ 1 ]
numbers[ 2 ]
numbers
2
4
6
values[ 0 ]
values[ 1 ]
values[ 2 ]
values
2
4
6
numbers[ 0 ]
numbers[ 1 ]
numbers[ 2 ]
numbers
2
4
6
values[ 0 ]
values[ 1 ]
values[ 2 ]
values
2
4
6
Figure 10.6 Comparison of Array Variables

Free download pdf