String里面的intern是个啥东东啊?

gangxuejava 2003-10-21 05:37:50
intern是干什么用的啊?咋用啊?
...全文
100 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjq1980 2003-10-21
  • 打赏
  • 举报
回复
好问题,谢谢楼主!
Veeve 2003-10-21
  • 打赏
  • 举报
回复
补充一下:
String s1 = "aaa";
String s2 = "aaa";
这样子的s1 == s2会返回true,这种方式会首先从String池中取(相当于调用intern())字符串,所以得到s2的时候实际上返回的是跟s1同一个对象的引用。

而这样子的话:
String s1 = new String("aaa");
String s2 = new String("aaa");
s1 == s2 返回的是false,因为不再从池中取了,所以s1和s2不再是同一个引用

(当然这两种情况的equals()都是true)
我想这样能够看出intern() 的效果了吧
binny 2003-10-21
  • 打赏
  • 举报
回复
说说我的理解,有一个存放String的池。调用某个string的intern方法的时候,会到这个池用寻找与这个string equals的String,如果没有,就把这个string放到池里面,如果有,就使这个string指向池中的String。所以intern之后的String相同内容的就指向同一个对象,所以就可以用==来代替equals比较
vampire1129 2003-10-21
  • 打赏
  • 举报
回复
将共享池中的一字符串与一外界字符串比较如相等则返回共享池中的字符串
如不同则将外界字符串假如共享池并返回该字符串的句柄
yangjuanli 2003-10-21
  • 打赏
  • 举报
回复
if(a1.intern()==a2.intern()) System.out.println("aaa");
等价于(a1.equals(a2)) 我想这样的好处是:比用a1.equals(a2)那样的速度快。
LoveRose 2003-10-21
  • 打赏
  • 举报
回复
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.

62,612

社区成员

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

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