java - 通过引用调用的行为不符合预期

标签 java object static pass-by-reference

请考虑这个简短的代码:

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/

相关文章:

java - Soap 调用 http ://www. w3schools.com/webservices/tempconvert.asmx

java - 在 Java 中使用嵌套枚举类型

java - "Your package name is not valid"Android 连接到 DEEZER

javascript - 如何使用base64转换所有数组/对象

c++ - 静态变量链接错误,C++

Java字节数组到字符串到字节数组

swift - Swift 可以将类/结构数据转换为字典吗?

c++ - 我只能从一个文件访问静态 fstream

c++ - 声明静态成员而不定义

javascript - React Redux 深度嵌套对象