返回信息流代码如下:
String s1 = “abc”;
For(int i = 0 ; i < 10000 ;i ++)
{
s1 + = “def”;
s1 = “abc”;
}
小弟初学Java,认为此过程创建了10001个String对象,求各位大神不吝赐教,帮忙分析一下。
这是一条镜像帖。来源:北邮人论坛 / java / #39346同步于 2015/3/19
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
java newString()创建了几个对象?
shuang
2015/3/19镜像同步47 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
【 在 lixing 的大作中提到: 】
: 错误。s1会不断循环指向常量池中的abc->abcdef->abc->abcdef...
: 如果你用的是String s1=new String("abc"),且循环里也是s1=new String("abc"),则会创建20001个对象。
你好,现在的情况是我不new对象,就是像我上面那么做,到底创建了几个对象呢?还望帮忙分析指教。谢谢啦!
【 在 lixing 的大作中提到: 】
: 错误。s1会不断循环指向常量池中的abc->abcdef->abc->abcdef...
: 如果你用的是String s1=new String("abc"),且循环里也是s1=new String("abc"),则会创建20001个对象。
我认为 首先s1 = “abc”;在常量池创建一个对象,
循环里s1 + = “def”; 语句每次在堆里创建一个新的对象,而 s1 = “abc”; 语句在常量池中找到"abc",直接使用,不用创建新的对象,所以我认为是1+10000次,不知道理解对不。
【 在 shuang 的大作中提到: 】
:
: 我认为 首先s1 = “abc”;在常量池创建一个对象,
: 循环里s1 + = “def”; 语句每次在堆里创建一个新的对象,而 s1 = “abc”; 语句在常量池中找到"abc",直接使用,不用创建新的对象,所以我认为是1+10000次,不知道理解对不。
语义确实是在堆里创建,但是JVM可以作弊。
还是引用一段Java Language Specification吧:
15.18.1. String Concatenation Operator +
If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.
The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).
An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.
For primitive types, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.
hashcode貌似是根据string的内容计算的。所以只要内容一样,hashcode就一样,不能区分是否是不同对象。
可以把产生的对象放在list里,比较对象的引用。
【 在 icyfox 的大作中提到: 】
: 凭什么第一个就在常量池里,后面的就在堆上?不要想当然
: 自己看
: [upload=1][/upload]
不对,s1+的时候 会重新创建字符串
【 在 shuang 的大作中提到: 】
:
: 我认为 首先s1 = “abc”;在常量池创建一个对象,
: 循环里s1 + = “def”; 语句每次在堆里创建一个新的对象,而 s1 = “abc”; 语句在常量池中找到"abc",直接使用,不用创建新的对象,所以我认为是1+10000次,不知道理解对不。
来自「北邮人论坛手机版」
不懂,bd
【 在 shuang 的大作中提到: 】
: 代码如下:
: String s1 = “abc”;
: For(int i = 0 ; i < 10000 ;i ++)
: ...................