为什么修改了ArrayList参数,但没有修改String参数? [英] Why is an ArrayList parameter modified, but not a String parameter?

查看:110
本文介绍了为什么修改了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;
    }
}



输出:



This outputs:

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

如果是 ArrayList ,则会检索添加的元素。
如果 String ,方法调用对传递的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字符串对象,添加的元素越来越多retrived。在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是按值传递而且字符串 s是不可变的



当你致电

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

When you call

markAsNull(ArrayList<String> str)

新参考名称 str 是为 al ArrayList 创建的>。当 str 上添加元素时,它会被添加到同一个对象中。稍后您将 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 +追加我; 通过附加给定字符串并将其分配给来创建一个新的 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天全站免登陆