简体   繁体   中英

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?

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.

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. This behaviour is essentially undefined.

FWIW, my Java 8 outputs this:

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. 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:

    (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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