java - 将数组传递给方法示例没有意义

标签 java arrays

我的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

请解释为什么会出现这种情况,以及如何以某种方式实现这一点,以使数组的值不被更改。

最佳答案

// What hapened here? We just made changes to array2[] but somehow those changes got applied to array[]??? how did that happen?

因为java是按引用值传递的。引用的副本将传递给该方法。该引用仍然指向原始数组。您对此引用执行的任何更改都将反射(reflect)在原始数组上。

how this could be implemented somehow so that the values of array are not changed.

一种方法是,在方法内创建新数组并为其分配此引用。

示例:

public static void modifyArray( int array2[] ) 
   {
      array2 = new int[10];
      //Copy only ten elements from outer array, which populates element at index 2.
      for ( int counter = 0; counter < array2.length; counter++ )
      array2[ counter ] *= 2;
   } 

现在,您对此引用执行的更新/操作将影响方法内创建的新数组,而不是原始数组。

查看此SO discussion了解更多信息。

关于java - 将数组传递给方法示例没有意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13833313/

相关文章:

java - 来自函数引用的谓词( boolean 类型)

java - 如何在 Java 中从 Selenium Webdriver 调用书签?

java - 将字符串从 Java 发送到 C(套接字)

php - 当我键入时从 MySQL 填充多个输入字段

java - 将存储在数字数组中的数字加一

java - 根据其中一列将输入文件分成多个文件

javascript - 将 spring java 对象传递给 javascript

arrays - 为什么Swift标准库中的reverse()函数会返回ReverseRandomAccessCollection?

javascript - 购物车数组未正确渲染,react.js

javascript - 在 JavaScript 函数中更改数组会更改函数外的数组?