055.154-Which statement is true?

theoffspring 2009-10-02 11:31:24
Given this method in a class:

21. public String toString() {
22. StringBuffer buffer = new StringBuffer();
23. buffer.append('<');
24. buffer.append(this.name);
25. buffer.append('>');
26. return buffer.toString();
27. }

Which statement is true?

A. This code is NOT thread-safe.
B. The programmer can replace StringBuffer with StringBuilder with no other changes.
C. This code will perform poorly. For better performance, the code should be rewritten:
return "<" + this.name + ">";
D. This code will perform well and converting the code to use StringBuilder will not enhance the
performance.

Answer: B


我认为A是对的,StringBuffer虽是线程安全的,但这段代码却不是线程安全的,如果是在单线程中使用,选B当然是可以的
...全文
121 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
lxxzhy 2009-10-02
  • 打赏
  • 举报
回复
A是不对的.

StringBuffer buffer = new StringBuffer();
是在toString方法里面定义的本地变量,是线程安全的.
swandragon 2009-10-02
  • 打赏
  • 举报
回复
buffer是局部变量,每次调用方法都生成新的对象
所以A不对

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧