简体   繁体   English

jdk7 和 jdk8 之间的 String 有什么区别?

[英]what is the difference of String between jdk7 and jdk8?

here i have the code below, I want to know why the same code produce different result in jdk7 and jdk8?这里我有下面的代码,我想知道为什么相同的代码在 jdk7 和 jdk8 中产生不同的结果?

String s3 = new String("1") + new String("1");
System.out.println(System.identityHashCode(s3));    //JDK7 1485288136 - JDK8 985655350
String s3i = s3.intern();
System.out.println(System.identityHashCode(s3i));   //JDK7 1485288136 - JDK8 804611486
System.out.println(System.identityHashCode(s3));    //JDK7 1485288136 - JDK8 985655350
String s4 = "11";
System.out.println(System.identityHashCode(s4));    //JDK7 1485288136 - JDK8 804611486
System.out.println(s3 == s4); // JDK7 true - JDK8 false

CORRECT正确的

Seems not because of JDK only, something about junit.似乎不是因为 JDK,而是关于 junit。

import org.junit.Test;

public class StringDemo {

    @Test
    public void test() {
        String s3 = new String("1") + new String("1");
        s3.intern();
        String s4 = "11";
        System.out.println(s3 == s4);
        // JDK7 true - JDK8 false
    }

    public static void main(String[] args) {
        String s3 = new String("1") + new String("1");
        s3.intern();
        String s4 = "11";
        System.out.println(s3 == s4);
        // JDK7 true - JDK8 true
    }

}

You're delving into implementation specifics of identityHashCode() and string interning that can, and do differ between various different versions.您正在深入研究identityHashCode()和字符串实习的实现细节,这些细节在各种不同版本之间可以并且确实有所不同。 This behaviour is essentially undefined.这种行为基本上是未定义的。

FWIW, my Java 8 outputs this: FWIW,我的 Java 8 输出这个:

1829164700
1829164700
1829164700
1829164700
true

...but that's not guaranteed of course: ...但这当然不能保证:

  • identityHashCode() can differ whenever any of the internal object state differs, or the algorithm differs - both of these can change between versions.任何内部对象状态不同或算法不同时, identityHashCode()可能会有所不同——这两种情况都可能在版本之间发生变化。 The value itself isn't meaningful apart from being equal (or not) to another value generated in the same way.除了与以相同方式生成的另一个值相等(或不相等)之外,该值本身没有意义。 This is why the hashcodes are not equivalent across versions.这就是为什么不同版本的哈希码不相同的原因。
  • intern() may not behave exactly the same way across versions, or even invocations (as you've witnessed in your junit example.) Specifically, it may not return the same string object that you passed in - all it guarantees is that: intern()跨版本甚至调用的行为可能不完全相同(正如您在 junit 示例中所看到的那样。)具体来说,它可能不会返回您传入的相同字符串对象 - 它保证的是:

    (returns) a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings. (返回)一个与此字符串具有相同内容的字符串,但保证来自唯一字符串池。

    This is why s3==s4 may or may not be true, and similarly why the comparison of the hashcodes between s3 and s4 may or may not differ.这就是为什么s3==s4可能是也可能不是真的,同样也是为什么s3s4之间的哈希码的比较可能不同也可能不同的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM