我的 Java 书中有一个示例程序对我来说毫无意义。基本上它将数组引用传递给方法。但是结果是数组本身被修改了,即使该方法没有返回值或其中的某些东西表明它在做一些事情而不是创建它自己的数组实例。
public class PassArray
{
public static void main( String[] args )
{
int[] array = { 1, 2, 3, 4, 5 };
System.out.println(
"Effects of passing reference to entire array:\n" +
"The values of the original array are:" );
for ( int value : array )
System.out.printf( " %d", value );
modifyArray( array ); // pass array reference to method modifyArray
System.out.println( "\n\nThe values of the modified array are:" );
// output the value of array (why did it change?)
for ( int value : array )
System.out.printf( " %d", value );
} // end main
// multiply each element of an array by 2
public static void modifyArray( int array2[] ) // so this accepts an integer array as an arguement and assigns it to local array array[2]
{
for ( int counter = 0; counter < array2.length; counter++ )
array2[ counter ] *= 2;
} // What hapened here? We just made changes to array2[] but somehow those changes got applied to array[]??? how did that happen?
//What if I wanted to not make any changes to array, how would implement this code so that the output to screen would be the same but the value in array would not change?
} // end class PassArray
请解释为什么会这样,以及如何以某种方式实现这一点,以便不改变数组的值。小号