Java Reference
In-Depth Information
d0=getRandomDieValue () ;
d1=getRandomDieValue () ;
d2=getRandomDieValue () ;
d3=getRandomDieValue () ;
d4=getRandomDieValue () ;
}
This version of the method falls short because it only changes the local variables d0 , d1 , d2 ,
d3 ,and d4 . If you call the method as follows: rollDice (d[0],d[1],d[2],d[3],d[4]) ,
then this will not work because the array will remain unchanged after the execution of the
method. Yet another implementation of the rollDice method is shown below.
public static int [] rollDice() {
int [] d = int [ NUMBER OF DICE ] ;
for ( int i=0;i
<
NUMBER OF DICE ;
i ++)
{
d[ i ] = getRandomDieValue () ;
return d;
}
This implementation is similar to the implementation that takes a single array as input.
However, the new implementation makes it clear that method generates a new array of dice
and does not read the old array of dice. Therefore, this last implementation of the method
is preferred. The method can be called from the main method as shown below.
dice = rollDice() ;
5.1.1 Deep versus Shallow Array Copy
One needs to be very careful when copying arrays. Consider the following example.
public class Test {
public static void main(String [] args) {
int a[]= new i n t []
{ 2,234,14,12,23,2 } ;
int b[]= new i n t [6];
b=a ;
b[3]=7;
System. out . println (a [ 3 ] ) ;
}
}
This looks like a very simple program. First, the arrays a and b are created. Then all
the elements of the a array are copied to the b array. The fourth element of the b array
is then changed (remember that index counting for arrays starts at 0). This should have
no effect on the a array and the number 12 should be printed (the fourth element of the a
array). However, we you run the program, then we will see that the number 7 is printed.
In order to understand this counterintuitive behavior, consider Figure 5.3. It shows the
initial setup. The variables a and b point to two different arrays. The line b=a is going
to make b equal to 1000. In other words, after the assignment both a and b will be equal
to 1000. Then when the line b[3]= 7 is executed, both the value of b[3] and a[3] will
change. Nothing will now point to the array at position 2000 and it will be purged by the
garbage collector. This type of array copy is known as shallow copy .
Search WWH ::




Custom Search