按值传递(StringBuilder 与 String) [英] Pass-by-value (StringBuilder vs String)

查看:47
本文介绍了按值传递(StringBuilder 与 String)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么 System.out.println(name) 输出 Sam 而不受方法的 concat 函数的影响,而 System.out.println(names) 输出 Sam4 作为方法的 append 方法的结果.为什么是 StringBuilder 而不是 String?通常,对对象的引用调用方法会影响调用者,所以我不明白为什么 String 结果保持不变.提前致谢

I do not understand why System.out.println(name) outputs Sam without being affected by the method's concat function, while System.out.println(names) outputs Sam4 as a result of the method's append method. Why is StringBuilder affected and not String? Normally, calling methods on a reference to an object affects the caller, so I do not understand why the String result remains unchanged. Thanks in advance

public static String speak(String name) {
    name = name.concat("4");
    return name;
}

public static StringBuilder test(StringBuilder names) {
    names = names.append("4");
    return names; 
}

public static void main(String[] args) {
    String name = "Sam";
    speak(name);
    System.out.println(name); //Sam
    StringBuilder names = new StringBuilder("Sam");
    test(names);
    System.out.println(names); //Sam4
}

推荐答案

因为当你调用 speak(name); 时,你在里面说话

Because when you call speak(name);, inside speak when you do

name = name.concat("4");

它创建一个新对象,因为 String 是不可变的.当您更改原始字符串时,它会创建一个新对象,我同意您正在返回它但您没有捕获它.

it creates a new object because Strings are immutable. When you change the original string it creates a new object,I agree that you are returning it but you are not catching it.

所以基本上你正在做的是:

So essentially what you are doing is :

name(new) = name(original) + '4'; // but you should notice that both the names are different objects.

试试

String name = "Sam";
name = speak(name);

当然,现在我认为没有必要解释为什么它与 StringBuilder 一起工作,除非您不知道 StringBuilder 是可变的.

Of course now I think there is no need to explain why it's working with StringBuilder unless if you don't know that StringBuilder is mutable.

这篇关于按值传递(StringBuilder 与 String)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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