3
    StringBuilder str = new StringBuilder("Today");
    str.append(" is ").append("a").append(" sunny ").append(" day.");

In the java code above, I understand that first I created an object of type StringBuilder. Then I used the object reference str to access the method append of the class StringBuilder. After this, I loose track. Is the method append used after str.append("is") inside the append method, or am I calling the same method in this class? Further, can anyone explain the flow of execution of the above statement. Which of the above append methods is executed first?

4

4 回答 4

6

方法的返回值appendStringBuilder对象本身。因此,您可以链接调用并向字符串添加更多字符。否则,代码将很难阅读,因为您必须每行都引用 StringBuilder 对象。

于 2012-05-27T12:02:55.427 回答
5

str.append(" is ")返回 StringBuilder 本身。您正在对该方法返回的对象调用方法。这和做的一样

user.getAddress().getStreet().charAt(0);

除了在您的代码中,每个append()方法调用都返回相同的对象,这允许将多个方法调用链接到同一个 StringBuilder。

于 2012-05-27T12:04:00.993 回答
3

考虑看看Builder Pattern(向下滚动到页面末尾)。基本上,对象总是返回自己,因此您可以链接许多命令。

于 2012-05-27T12:15:43.547 回答
1
StringBuilder str = new StringBuilder("Today");
str.append(" is ").append("a").append(" sunny ").append(" day.");

这里str.append(" is ")返回StringBuilder您再次调用 append("a")methnod 的对象。

str.append(" is ").append("a")再次返回StringBuilder参考,再次调用append(" sunny ")方法等等。

所以基本上你正在链接方法,就是这样。

于 2012-05-28T06:41:47.870 回答