关于String类的intern()方法

ffww77 2004-04-01 05:01:10
String s1,s2,s3,s4

s1 = new String("hello");
s2 = new String("hello");

s3 = s1.intern();
s4 = s2.intern();

经测试发现
s3==s4 True
s3==s1 False
s2==s4 False
s1==s4 False

这样的结果是不是正确
不是很理解intern()方法的意义,请大家解释一下。谢谢
...全文
38 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
danceflash 2004-04-01
  • 打赏
  • 举报
回复
String类型比较特殊
"hello"本身会放入字符串常量池
intern()好像就是用来返回该字符串在常量池中的引用(如果有的话)

有人说可以加快字符串比较的速度,不过我在现实中从来没用过 :P
CoolAbu 2004-04-01
  • 打赏
  • 举报
回复
看看Java API中的说法,也许会明白些。

public String intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

ffww77 2004-04-01
  • 打赏
  • 举报
回复
...

62,623

社区成员

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

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