java - Experimenting with String creation -
i found interesting case while testing string creation , checking hashcode.
in first case 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 expected output interned string picks reference string pool whereas s1 picks reference of new object. identity hash code different.
now if create string using char array see 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 unexpected output. how can interned string , new string object have same identityhashcode??
any ideas?
in first case, myteststring
literal on pool before call intern
, whereas in second case not string s5
put in pool directly.
if go through examples step step, happens:
string s1 = new string("myteststring");
=> use of string literal creates stringmyteststring
in pool (let's calls0
), , new strings1
created, not in pool.string s3 = s1.intern();
=> checks if there equivalent string in pool , findss0
.s3
,s0
refer same instance (i.e.s3 == s0
true,s1 != s0
).
in second example:
string s5 = new string(c1);
creates new string, not in poolstring s6 = s5.intern();
checks ifmyteststring
in pool can't find it, callintern
creates new string reference in pool refers same strings5
.s6 == s5
true.
finally can run these 2 programs confirm explanation (the second 1 prints true
3 times):
public static void main(string[] args) { string s1 = new string("myteststring"); string s3 = s1.intern(); system.out.println("myteststring" == s1); system.out.println(s3 == s1); system.out.println("myteststring" == s3); } public static void main(string[] args) { string s1 = new string(new char[] {'m', 'y', 't', 'e', 's', 't', 's', 't', 'r', 'i', 'n', 'g'}); string s3 = s1.intern(); system.out.println("myteststring" == s3); system.out.println("myteststring" == s1); system.out.println(s3 == s1); }
Comments
Post a Comment