我是编程方面的新手,以及本网站,所以请原谅我,如果我搞砸了。我有一段时间搞清楚如何在这里正确发布我的代码。什么时候'void'方法影响参数?它何时影响原始对象?
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'?**
}
}
所以我的问题基本上是在那里输入的评论。为什么传入方法的数组在传递给另一个方法的int不更改时会更改原始数组(x [])的值?我相信这是一个简单的答案,但是当我做了我的研究时,我无法弄清楚要搜索什么。我不知道这是叫什么,所以我搜索的所有东西都导致我错误的方式。谢谢你的帮助!!
编辑:感谢您的地址类比!这是你可以向我解释的最好方式。所以基本上当你将一个数组传递给一个参数时,它传递的是一个引用,而不是实际的值?所以当我在我的方法中进行调整时,它会改变阵列引用的内容。 我注意到这也发生在一个列表中。所以这个列表实际上并没有按值传递?看来,如果数组/列表本身基本上是通过在编辑,不管我我的方法中的命名(一[]在这种情况下)。
编辑http://javadude.com/articles/passbyvalue.htm此页面确实清除它。抱歉发布重复的问题。问题是我不知道我想问什么。我从来没有听说过这些术语“传值/参考”,所以现在我知道
对这个问题的更好的答案之一,已经被这么多的形式已经问过:http://stackoverflow.com/a/9404727/680925 – Perception 2013-04-07 17:59:38
可能重复[是Java“传递参考”? ](http://stackoverflow.com/questions/40480/is-java-pass-by-reference) – delnan 2013-04-07 18:04:57