我刚开始学习编程,也是第一次使用这个网站,如果我有什么失误请谅解。我遇到了一个麻烦,不知道如何正确地在这里发布我的代码。
package tester;
import java.util.*;
public class Mainclass2 {
public static void main(String[] args) {
int y = 3;
int[] x = {1, 2, 3, 4};
editnumbersArray(x);
editnumbersNotArray(y);
System.out.println(x[2]); **//now this was changed from 3 to 9...**
System.out.println(y); //but this one went unchanged.
}
//this accepts 'x[]' into the 'a[]' parameter.
public static void editnumbersArray(int[] a){
a[2] = 9; **//<---why does this one CHANGE the actual x[2] instead of just a[2]?**
}
//this accepts 'y' into the 'a' parameter.
public static void editnumbersNotArray(int a){
a = 9; **//<--while this one only changes 'a' instead of 'y'?**
}
}
所以我的问题基本上是在评论中输入的。为什么传递到方法中的数组会改变原始数组(x[])的值,而传递到其他方法中的int却不会改变呢?我相信这是一个简单的答案,但是当我进行调查时,我无法弄清楚要搜索什么。我不知道这叫什么,所以我搜索的一切都引导我走了错误的方向。谢谢任何帮助!
编辑:感谢那个用地址比喻的例子!这绝对是你可以向我解释的最好方式。所以基本上当你将一个数组传递到参数中时,它传递的是一个引用,而不是实际的值?因此,当我在我的方法内进行调整时,它会更改数组正在引用的任何内容?
我注意到这也发生在列表中。因此,列表实际上并没有按值传递?似乎数组/列表本身只是被传递进来进行编辑,无论我在方法中给它命名什么(在这种情况下是a[])。
编辑:http://javadude.com/articles/passbyvalue.htm 这个页面真正澄清了它。很抱歉发布了重复的问题。问题在于我不知道自己想问什么。我甚至从未听说过这些术语“按值/引用传递”,所以现在我知道了。