返回信息流StringBuffer d = new StringBuffer("abc");
d = d.append("567");
产生了几个对象??
这是一条镜像帖。来源:北邮人论坛 / java / #28981同步于 2014/3/24
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
一道与常量池有关的面试题
taoch
2014/3/24镜像同步5 回复
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
java程序猿面试宝典上给的答案是2个(不是原题,没有疑问的部分略去了)
我个人的理解,d肯定是一个对象,"abc"和"567"都是在编译期就进常量池了。append不产生新对象。所以总共3个
不知道哪里理解的有问题没
【 在 taoch (不知道叫什么昵称好。。。) 的大作中提到: 】
: StringBuffer d = new StringBuffer("abc");
: d = d.append("567");
: 产生了几个对象??
: ...................
一样觉得很困惑。。。
个人觉得是3个,两个String在常量池中,一个StringBuffer在堆中,还有一个引用d不算对象
大神可以帮忙解释吗?@nuanyangyang~~~
不知道。实现相关。
有一种优化叫“逃脱分析”。如果编译器对StringBuffer有特殊知识(一般应该有吧),有可能把它去掉。
对于字符串常量,JLS说,在装载包含字符串常量的类或接口的时候,有可能(may)创建实例(如果以前曾经intern过这个字符串,就有可能不会(might not)创建了)。
http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.5
Loading of a class or interface that contains a String literal (§3.10.5) may create a new String object to represent that literal. (This might not occur if the same String has previously been interned (§3.10.5).)
对于字符串常量表达式,只说了一定会intern,但没有说什么时候创建实例。
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28
Constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern.
另外,JLS说过,就算是("abc"+ x + "def" + y + "ghi" + z + w)这样的表达式,具体实现都可以把它变成StringBuffer。
http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.18.1
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.