简体   繁体   English

字符串不变性问题

[英]String immutability question

I know that Java strings are immutable.我知道 Java 字符串是不可变的。 However, when I run the function below, the output is not what I expect it to be.但是,当我运行下面的 function 时,output 并不是我所期望的。

    public static void main(String[] args) {
        String s = "wicked";
        String [] ss = new String [1];
        ss[0] = "witch";
        modify(s, ss);
        System.out.println(s+" "+ ss[0]);
    }
    private static void modify(String s, String[] ss) {
        s = "sad";
        ss[0] = "sod";          
    }

The output I get is wicked sod , and not wicked witch as I expected it to be.我得到的 output 是wicked sod ,而不是我预期的wicked witch Is it because I am passing an array reference as the second argument to the modify function as opposed to passing the String object itself?是否因为我将数组引用作为第二个参数传递给修改 function 而不是传递字符串 object 本身? Any clarification is highly appreciated.任何澄清都非常感谢。

You've changed the contents of the array - arrays are always mutable.您已更改数组的内容 - arrays 始终是可变的。

The array initially contains a reference to the string "witch".该数组最初包含对字符串“witch”的引用。 Your modify method changes the array to contain a reference to the string "sod".您的modify方法将数组更改为包含对字符串“sod”的引用。 None of the strings themselves have been changed - just the contents of the array.没有任何字符串本身被更改 - 只是数组的内容。

(Note that the value of ss[0] isn't a string - it's a reference to a string.) (请注意, ss[0]的值不是字符串 - 它是对字符串的引用。)

Is it because I am passing an array reference as the second argument to the modify function as opposed to passing the String object itself?是否因为我将数组引用作为第二个参数传递给修改 function 而不是传递字符串 object 本身?

Exactly.确切地。 You are passing a reference to a mutable object (the array).您正在传递对可变 object (数组)的引用。 When the method changes this object, the changes will be visible outside the method.当方法更改此 object 时,更改将在方法外部可见。

Read a VERY good article about passing method parameters by Yoda Parameter passing in Java - by reference or by value?阅读一篇关于通过 Yoda 传递方法参数的非常好的文章Java 中的参数传递 - 通过引用还是通过值?

Strings being immutable means that you cannot change "hello world" to "hello".字符串不可变意味着您不能将“hello world”更改为“hello”。 But you can assign an entire new string.但是您可以分配一个全新的字符串。 And this is what you are doing here.这就是你在这里所做的。

You are giving reference to an array object.您正在引用数组 object。 That's why the contents of the array are changed.这就是改变数组内容的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM