修改非不可变对象,java

Modify non immutable object, java

我对这个例子感到困惑:

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 而它不会创建异常?

我的想法:
我有一个 StringBuilder,一个非不可变对象,如果我在该对象上使用一种方法,它将 return 给我一个具有相同引用对象的对象的新值。

.substring() 方法返回一个 new String 对象,它不会修改 StringBuilder 本身。

Why when i am using a.substring ( int a, int b ) it is not modifying the object StringBuilder ?

因为substring() returns一个新字符串,它不会修改StringBuilder

char ch = a.charAt(4); , charAt() returns 基于索引的字符,因为索引是零基,它 returns e.

仅仅因为对象是 'mutable' 并不意味着对象可以执行的每个方法都必须修改它。常见示例是 equals()、getClass() ... append() 但是 确实 修改了 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.

  • 一个方法并不总是会return你引用同一个对象。它可能会创建一个新对象 return 。在你假设任何事情之前检查 docs 总是更好。

Why when I am using a.substring ( int a, int b ), it is not modifying the object StringBuilder?

  • 如果您阅读 documentation,它清楚地指出 substring(int,int) 方法 Returns 一个 new String。这回答了为什么你的对象没有被修改。

Why if I use the method a.append("value") I am modifying the value of the StringBuilder object?

  • 同样,如果您阅读 docs for append(String),它清楚地指出它 - Returns:对 这个对象的引用。 。此方法符合 "your thinking" 的要求。