为什么 ArrayList 参数被修改,而不是 String 参数? [英] Why is an ArrayList parameter modified, but not a String parameter?

查看:21
本文介绍了为什么 ArrayList 参数被修改,而不是 String 参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class StackOverFlow {
    public static void main(String[] args) {
        ArrayList<String> al = new ArrayList<String>();
        al.add("A");
        al.add("B");
        markAsNull(al);
        System.out.println("ArrayList elements are "+al);

        String str = "Hello";
        markStringAsNull(str);
        System.out.println("str "+ str);
    }
    private static void markAsNull(ArrayList<String> str){
        str.add("C");
        str= null;
    }
    private static void markStringAsNull(String str){
        str = str + "Append me";
        str = null;
    }
}

输出:

ArrayList elements are [A, B, C]
str Hello

ArrayList 的情况下,添加的元素正在被检索.在 String 的情况下,方法调用对传递的字符串没有影响.JVM 到底在做什么?谁能详细解释一下?

In the case of ArrayList, the added elements are getting retrieved. In case of String the method call has no effect on the String being passed. What exactly is the JVM doing? Can anyone explain in detail?

推荐答案

在 Arraylist 字符串对象的情况下,添加的元素正在被检索.在 String 的情况下,方法调用对传递的 String 没有影响.

In the case of Arraylist string objects the added elements are getting retrived. In case of String the method call has no effect on the String being passed.

它的发生是因为 Java 是按值传递的,而 Strings 是不可变的

当你打电话

It happens cause Java is Pass-by-Value and Strings are immutable

When you call

markAsNull(ArrayList<String> str)

al 指向的同一个 ArrayList 创建一个名为 str 的新引用.当您在 stradd 一个元素时,它会被添加到同一个对象中.稍后您将 str 设置为 null 但该对象添加了新值并由 a1 指向.

The a new reference by name str is created for the same ArrayList pointed by al. When you add an element on str it gets added to same object. Later you put str to null but the object has the new values added and is pointed by a1.

打电话时

markStringAsNull(String str)
{
    str = str + "Append me";
    // ...
}

str = str + "Append me"; 通过附加给定的字符串创建一个新的 String 对象并将其分配给 str.但同样它只是对实际字符串的引用,该字符串现在指向新创建的字符串.(由于不变性)并且原始字符串没有改变.

The line str = str + "Append me"; creates a new String object by appending the given string and assignes it to str. but again it is just reference to actual string which now pointing to newly created string. (due to immutablity) and the original string is not changed.

这篇关于为什么 ArrayList 参数被修改,而不是 String 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆