2014-06-12 34 views

回答

3
String str= new String("abc").intern() // calling intern() will add the String object to the String pool. 
+3

但是请记住,事后使用'intern'的返回值而不是'new String(“abc”)',否则,您将无法对字符串进行操作! – gexicide

+1

''“abc”.intern()''请。所以字符串不会被创建两次。 –

+1

@Vakh:但''abc“.intern()'是废话。无论如何,字符串文字都是实用的。好的,'new String(“abc”)'更糟糕:)。实习'abc'最简单的解决方案就是''abc''。 – gexicide

1

如果你的对象实际上是new String("abc"),那么你应该只使用​​,而不是创建一个新的字符串和实习这一块。无论如何,​​是无所不用的,因为所有字符串都是。

即低于布尔运算将是真正的

"abc" == new String("abc").intern() 
+0

有道理..“abc”已经被添加到字符串池中。 – TheLostMind

0

好了,你不要一个字符串转换为StringPool。 StringPool是由JVM管理的字符串集合。 但是,通过请求虚拟机使用字符串对象的intern()方法(如果它尚未创建为文字)(否则它已经存在),可以请求包含在池中的字符串

String test= "test".append("Case").append("String"); 
    test.intern(); //string "testCaseString" will be interned 

    String check= "InternString"; 
    check.intern(); //redundant as the string was already interned in the above creation statement 
+0

so intern()不是有用的吗? – Hitendra

+0

当然,如果您创建或构建您的字符串,或者从您不知道如何创建它的对象中获取该字符串,那么它是有用的。 这只是多余的,如果字符串被创建为文字 –

+0

好的谢谢你Satyan Raina :) – Hitendra