在此字符串操作期间将创建多少个对象? [英] How many objects will be created during this string operation?

查看:206
本文介绍了在此字符串操作期间将创建多少个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是实例方法中的代码片段

Below is code snippet in instance method

 String x = new StringBuffer().append("a").append("b").append("c").toString()

我受到了印象,创建第一个新的stringbuffer,然后在字符串缓冲区的前面添加a,类似于b和c的
。之后,将stringbuffer转换为字符串。因此,就我而言,创建了2个对象(一个用于字符串缓冲区,另一个用于字符串)。
对吗?基本上,就我而言,不会为字符串a,b,c创建中间对象。这是对的吗?

i am under impression , first new stringbuffer is created, then a is appended atlast of string buffer, similarly b and c. After that stringbuffer is converted to string. So as per me 2 objects are created(one for string buffer and another for string). correct? Basically as per me no intermediate objects will be created for String "a","b","c". Is this right?

编辑: - 根据所有回复,看起来会为字符串文字创建对象a,b, c但如果我通过链接 http ://docs.oracle.com/javase/1.4.2/docs/api/java/lang/StringBuffer.html#toString (),这不应该创建临时字符串。搜索总的来说,这可以避免创建许多临时字符串。在这个链接上。同意它适用于1.4.2但我希望基本保持相同的1.6

- as per all of the replies, looks like objects will be created for string literals "a","b","c" But if i go by link http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/StringBuffer.html#toString(), this should not create temporary strings. Search "Overall, this avoids creating many temporary strings." on this link. Agreed it is for 1.4.2 but i hope fundamental remain same for 1.6

是的,如果我在下面而不是超过五个对象将被创建。三个为a,b,c。一个字符串缓冲区。然后最后从
stringbuffer转换为字符串。对于a,b,c以及最后一个字符串abc的对象将太过池并且终身存在

Yes if i do below instead of above five objects will be created. three for "a","b","c" . one for string buffer. Then at last for string converted from stringbuffer. objects for "a","b","c" and lastly string "abc" will go too pool and be there in for life time

String str1="a";
String str2="b";
String str3="c";
String x = new StringBuffer().append(str1).append(str2).append(str3).toString()

以上理解是否正确?

推荐答案

没有区别根据创建的对象数量,在第一个和第二个代码段之间。字符串abc将参与此过程,但可以使用他们的实习副本。如果没有对 str1..str3 的进一步引用,编译器可以自由地将第二个片段转换为第一个片段,从而消除变量。

There is no difference between your first and second snippet in terms of how many objects are created. Strings "a", "b", and "c" will participate in the process, although their interned copies may be used. In the absence of further references to str1..str3, the compiler is free to transform your second snippet into your first one, eliminating the variables.

此外, StringBuffer 追加内可能有内部重新分配,如果内部字符串中的内存不足以保存附加的数据。这只是理论上的可能性,但它就在那里。

In addition, there may be an internal reallocation inside StringBuffer's append, if the memory in its internal string is insufficient to hold the data being appended. This is only a theoretical possibility, but it is there.

这篇关于在此字符串操作期间将创建多少个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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