修改非不可变对象,java [英] Modify non immutable object, java
问题描述
我对这个例子感到困惑:
I am confused with this example :
StringBuilder a = new StringBuilder("abcde");
String subStr = a.substring( a.indexOf("a") , a.indexOf("c") );
int leng = a.length();
char ch = a.charAt(4);
System.out.println( subStr + " " + leng + " " + ch);
//the result will be : subStr = abc , leng = 5 ch = e
我的问题是:为什么 ch = e 并且它不会创建异常?
My question is : Why ch = e and it doesn't create an Exception ?
我的想法:
我有一个 StringBuilder,一个非不可变对象,如果我在对象上使用一个方法,它将返回一个具有相同引用对象的对象的新值.
My thinking:
I have one StringBuilder, a non immutable object and if I use a method on the object it will return me a new value of the object with the same reference object.
- 为什么当我使用
a.substring ( int a, int b )
时,它没有修改对象 StringBuilder ? - 为什么如果我使用方法
a.append("value")
我正在修改 StringBuilder 对象的值?
- Why when I am using
a.substring ( int a, int b )
, it is not modifying the object StringBuilder ? - Why if I use the method
a.append("value")
I am modifying the value of the StringBuilder object?
推荐答案
我有一个 StringBuilder,一个非不可变对象,如果我在对象上使用一个方法,它将返回一个具有相同引用对象的对象的新值.
I have one StringBuilder, a non immutable object and if I use a method on the object it will return me a new value of the object with the same reference object.
- 方法并不总是返回相同的引用对象.它可能会创建一个新对象并返回它.最好先查看 docs假设任何事情.
- 如果您阅读了 文档,它清楚地说明
substring(int,int)
方法返回一个新字符串.这回答了为什么您的对象没有被修改. - 如果您阅读了 docs 用于
append(String)
,它清楚地说明它 - 返回:对 这个对象的引用..这种方法符合你的想法". - Again if you read the docs for
append(String)
, it clearly states that it - Returns: a reference to this object.. This method complies with what "your thinking" was.
为什么当我使用 a.substring ( int a, int b )
时,它没有修改对象 StringBuilder
?
Why when I am using
a.substring ( int a, int b )
, it is not modifying the objectStringBuilder
?
为什么如果我使用方法 a.append("value")
我正在修改 StringBuilder
对象的值?
Why if I use the method
a.append("value")
I am modifying the value of theStringBuilder
object?
这篇关于修改非不可变对象,java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!