请考虑这个简短的代码:
class abs{}
class cd
{
static void method(abs a)
{
System.out.println(a); // PRINTS NULL
a = new abs();
System.out.println(a); // PRINTS NEWLY GENERATED HASHCODE
}
public static void main(String...args)
{
abs gh = null;
// REFERENCE SET TO NULL
// NOW PASSING IT TO A METHOD
method(gh);
// IF OBJECT CALL IS CALL BY REFERNCE, THEN WHY DOES THIS PRINT NULL ?
System.out.println(gh);
}
}
我的评论解释了我想要什么。基本上最后一个打印语句应该打印哈希码,但它打印“null”。这背后的原因是什么?
最佳答案
Java is pass by value 。这是您的代码中发生的情况:
//gh initialized as null
abs gh = null;
//passing a copy of the value of the reference to the method
method(gh);
//gh keeps the value of the current reference which is null
System.out.println(gh);
一个更好的例子是当尝试替换通过 List
迭代时获得的对象时:
List<String> stringList = Arrays.asList("hello", "world");
System.out.println(stringList);
for (String currentString : stringList) {
//naively trying to change the contents from ["hello", "world"] to ["bye", "world"]
if (currentString.equals("hello")) {
currentString = "bye";
}
}
System.out.println(stringList);
输出:
["hello", "world"]
["hello", "world"]
这是因为增强的 for
循环将使用迭代器提供的引用副本。上面的for
循环代码可以翻译成这样:
for (Iterator<String> it = stringList.iterator(); it.hasNext(); ) {
String currentString = it.next();
//now, it's more clear that you're updating the variable currentString
//that holds a copy of the reference stored in the List
//this explains why this approach won't work
if (currentString.equals("hello")) {
currentString = "bye";
}
}
关于java - 通过引用调用的行为不符合预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25208904/