为什么 JDK 1.4 和 1.5 的输出不同?

2024-02-04

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

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");
}

outputs:

  • 在jdk 1.4上

    str[3]
    equals result[true]
    if
    
  • 在jdk 1.5上

    str[3]
    equals result[false]
    else
    

根据这一页 http://www.coderanch.com/t/250475/java-programmer-SCJP/certification/toString-Integer-class, the Integer#toString方法(由String#valueOf(int))在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。

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

注意:正如已经提到的,javadocInteger#toString没有说明返回的字符串是否会被保留,因此问题中的两个输出同样有效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 JDK 1.4 和 1.5 的输出不同? 的相关文章

随机推荐