为什么要使用String intern方法?

12

此帖所解释,String字面量会自动池化,但使用new关键字构建的对象则不会,因此需要使用intern方法。但即使使用intern方法,仍然会创建一个新对象,那么intern方法有什么用呢?

String s = "Example";

String s1 = new String("Example"); // will create new object

String s2 = new String("Example").intern(); // this will create new object
 // but as we are calling intern we will get reference of pooled string "Example"

现在

System.out.println(s == s1); // will return false
System.out.println(s == s2); // will return true
System.out.println(s1 == s2); // will return false

intern方法有什么用途呢?

编辑

我已经理解了intern方法的工作原理,但我的问题是为什么要使用intern方法?因为要调用intern方法,我们必须使用new创建字符串对象,这将创建字符串的新实例!

String s3 = new String("Example"); // again new object

String s4 = s3.intern();

System.out.println(s3 == s4); // will return false

因此,调用intern方法将不会将s3指向池中的字符串。 intern方法将返回对池中字符串的引用。

另外,如果尚未池化,则调用intern方法将推送字符串到池中?这是否意味着每次调用任何字符串上的intern都将被推送到池中?


2
https://dev59.com/JXI-5IYBdhLWcg3weoTR - Aniket Kulkarni
1
坦白地说,它没有用处。 - Boann
3个回答

12

.intern()的基本算法如下:

  1. 创建一个字符串哈希集合
  2. 检查当前处理的字符串是否已在集合中
  3. 如果是,则返回集合中的该字符串实例
  4. 否则,将该字符串添加到集合中并返回它的实例

因此,它基本上用于查找给定的字符串是否存在于池中,如果存在,则获取该字符串的相同实例;否则,为新字符串创建一个新实例。


1
这里是事件序列:

String s = "Example";

在池中创建一个字符串字面量。

String s1 = new String("Example");

// will create new object <-- Correct, just create a new object

String s2 = new String("Example").intern(); //

只有在字符串常量池中找不到字符串文字“Example”时,才创建对象。在这种情况下,将返回s1。

我希望您能看到这里的intern实际上为您提供了使用来自池中的字符串的选项。 而且在Java中,所有的字符串都是对象; 因此,池实际上是具有完全相同字符序列的字符串的引用。

我记得在stackoverflow上有一个非常好的线程; 为您找到了它.. 只需检查这个链接,它很棒 Is String Literal Pool a collection of references to the String Object, Or a collection of Objects


0
该方法返回字符串对象的规范表示。因此,对于任何两个字符串a和t,只有当s.equal(t)为true时,s.intern()==t.intern()才为true。
以下是您的语法:--
public String intern ()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接