I found an interesting case while testing with string creation and checking their hashcode.
In first case i created string using copy constructor:
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
String s1 = new String("myTestString");
String s3 = s1.intern();
System.out.println("S1: " + System.identityHashCode(s1) + " S3:"
+ System.identityHashCode(s3));
}
}
Output of above code is:
S1: 816115710 S3:478684581
This is expected output as interned string picks the reference from String pool whereas s1 picks reference of new object. So their identity hash code is different.
Now if i create String using char array then i see some strange behavior:
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
char[] c1 = { 'm', 'y', 'T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n',
'g' };
String s5 = new String(c1);
String s6 = s5.intern();
System.out.println("S5: " + System.identityHashCode(s5) + " S6:"
+ System.identityHashCode(s6));
}
}
Output of above code is:
S5: 816115710 S6:816115710
This is an unexpected output. How can interned String and new String object have same identityhashcode??
Any ideas?