String类的intern()方法疑惑

intern()方法在官方文档上的解释如下:

intern
public String intern()返回字符串对象的规范化表示形式。
一个初始为空的字符串池,它由类 String 私有地维护。

当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(用 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并返回此 String 对象的引用。

它遵循以下规则:对于任意两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 才为 true。

所有字面值字符串和字符串赋值常量表达式都使用 intern 方法进行操作。字符串字面值在 Java Language Specification 的 §3.10.5 定义。

返回:
一个字符串,内容与此字符串相同,但一定取自具有唯一字符串的池。
---------------------------------------------------------------------------------
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.

All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification

Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
----------------------------------------------------------------------------------
放测试代码如下:
代码一
class StringDemo
{
    public static void main(String[] args)
    {
        String param = new String("param"+"a");
        String paramsame = param.intern();
        System.out.println(param==paramsame);
    }
}
按照官方文档的描述运算,这里会输出false,实际运行情况也是输出false;
---------------------------------------------------------
代码二
class StringDemo
{
    public static void main(String[] args)
    {
        String a="a";
        String param = new String("param"+a);
        String paramsame = param.intern();
        System.out.println(param==paramsame);
    }
}
按照官方文档的描述,这里同样会输出false,但实际输出的是true。

---------------------------------------------------------------------
当String对象在调用intern()方法时,如果在常量池没有String对象(如上面的param)的字面量时,即没有equals(param)时,intern方法可能会分情况把param的字面量或者是引用添加到常量池,而不是对官方文档常规上理解的把param的字面量添加到常量池。

1:在代码一中,String param=new String("param"+"a"),new里面的参数是一个String直接量,即是字面量,当param.intern()时会判断param的字面量在常量池中有没有,如果没有则把param的[color=red]字面量添加到常量池中


2:在代码二中,String param=new String("param"+a),new里面的参数不是一个String的直接量,即不是字面量,它带有一个引用变量a,所以当param.intern()的时候,会判断在常量池中有没有param的字面量,如果没有则把param的引用,即是一个哈希地址值(?)添加到常量池中。所以paramsame和param这两个引用变量的地址值一样,paramsame==param时输出true。用hashCode()方法查看param和paramsame时一样。(//貌似这句废话了)。[/color]



参考链接:
1:http://www.zhihu.com/question/36908414
2:http://www.iteye.com/topic/1112592

本来此文是打算一如既往在新浪的博客上发布的,但新浪提示我有非法字符,这么多字不知道怎么找非法字符..所以这成了我在iteye的首文。

猜你喜欢

转载自zsdxqsjx.iteye.com/blog/2252860