为什么JDK 1.4和1.5之间的输出不同? [英] Why the output is different between JDK 1.4 and 1.5?

查看:140
本文介绍了为什么JDK 1.4和1.5之间的输出不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JDK 1.4和1.5运行此代码并获得不同的结果。为什么会这样?

I'm running this code with JDK 1.4 and 1.5 and get different results. Why is it the case?

String str = "";
int test = 3;

str = String.valueOf(test);
System.out.println("str[" + str + "]\nequals result[" + (str == "3") + "]");

if (str == "3") {
    System.out.println("if");
} else {
    System.out.println("else");
}

输出:


  • on jdk 1.4

  • on jdk 1.4

str[3]
equals result[true]
if


  • on jdk 1.5

  • on jdk 1.5

    str[3]
    equals result[false]
    else
    


  • 推荐答案

    根据此页面整数#toString 方法(由 String#valueOf(int))在1.4中实现如下:

    According to this page, the Integer#toString method (which is called by String#valueOf(int)) is implemented like this in 1.4:

    public static String toString(int i) {  
        switch(i) {  
            case Integer.MIN_VALUE: return "-2147483648";  
            case -3: return "-3";  
            case -2: return "-2";  
            case -1: return "-1";  
            case 0: return "0";  
            case 1: return "1";  
            case 2: return "2";  
            case 3: return "3";  
            case 4: return "4";  
            case 5: return "5";  
            case 6: return "6";  
            case 7: return "7";  
            case 8: return "8";  
            case 9: return "9";  
            case 10: return "10";  
        }  
        char[] buf = (char[])(perThreadBuffer.get());  
        int charPos = getChars(i, buf);  
        return new String(buf, charPos, 12 - charPos);  
    }
    

    这可以解释你的结果,因为字符串文字 3被实习,3==3总是返回true。

    That would explain your result because the string literal "3" is interned and "3" == "3" always returns true.

    您可以尝试10和11来验证这一点。

    You can try with 10 and 11 to verify this.

    注意:如前所述,整数#toString 没有说明返回的字符串是否会被实习,因此你问题中的两个输出同样有效。

    Note: as already mentioned, the javadoc of Integer#toString does not say whether the returned string will be interned or not so both outputs in your question are equally valid.

    这篇关于为什么JDK 1.4和1.5之间的输出不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆