stringbuilder中string和substring()方法的不变性 [英] Immutability of string and substring() method in stringbuilder

查看:449
本文介绍了stringbuilder中string和substring()方法的不变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code 1:
    StringBuilder sb1 = new StringBuilder("123456");
    sb1.substring(2, 4);
    sb1.deleteCharAt(3);
    sb1.reverse();
    System.out.println(sb1);



输出:

65321




output :
65321

code 2:
String s = "java2s".replace('a', 'Z').trim().concat("Aa");//line 1
    s.substring(0, 2);//line 2
    s.concat("Bb");//line 3
    System.out.println(s);



输出:

jZvZ2sAa



我尝试过:



代码1:在java中String是不可变的,而StringBuilder和StringBuffer是可变的,但是,为什么substring()方法不会在sb1中进行任何更改,即使它是a StringBuilder对象?



代码2:在第1行中,concat()方法对字符串java2s进行了更改,但为什么它没有'第3行发生了吗?



有谁能请清除我的疑惑?

提前谢谢。


output :
jZvZ2sAa

What I have tried:

code 1 :In java String is immutable whereas StringBuilder and StringBuffer are mutable but, why substring() method doesn't make any changes in sb1 even though its a StringBuilder object?

code 2:In line 1 concat() method made a change in the String "java2s" but why it doesn't happen so in line 3?

Could anyone please clear my doubts?
Thanks in advance.

推荐答案

1。 substring 方法返回指定的字符,它不会影响现有的字符串。请参阅 substring(Java Platform SE 7) [ ^ ]。



2. concat 方法通过将原始字符串连接到新字符串来创建新字符串字符,并返回新创建的字符串。原件保持不变;这就是不可变的意思。
1. The substring method returns the specified characters, it does not affect the existing string. See substring (Java Platform SE 7 )[^].

2. The concat method creates a new string by concatenating the original with the new characters, and returns the newly created string. The original remains unchanged; that is what immutable means.


因为substring返回一个新字符串,所以它不会以任何方式影响原始字符串,无论是字符串还是字符串构建器。



Concat做同样的事情:它返回一个新的字符串,它是参数的组合 - 它不会以任何方式影响输入。



将其视为数字:

Because substring returns a new string, it does not affect the original in any way, be it a string or a stringbuilder.

Concat does the same thing: it returns a new string which is a combination of the parameters - it doesn't affect inputs in any way.

Think about it as numbers:
24 + 77

返回值101 - 它不会更改数字24或77到101,你不会指望它。那么为什么你期望用你的第二个名字连接你的名字呢?如果我连接我的:保罗和格里芬正确,我得到一个不同的对象,我的正式名称:保罗格里芬。这并没有改变我母亲曾经叫我的东西:保罗,或者警察叫我的:格里芬先生。

Returns the value 101 - it doesn't change the number 24 or 77 to 101 and you would not expect it to. So why would you expect concatenation of your first name with your second name to change either? If I concatenate mine: "Paul" and "Griffin" correctly, I get a different object, my "formal name": "Paul Griffin". That doesn't change what my mother used to call me: "Paul", or what policemen call me: "Mr Griffin".


这篇关于stringbuilder中string和substring()方法的不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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