Why does the String.intern() method return two different results? [duplicate]

旧街凉风 提交于 2019-11-28 07:19:27

问题


I have the code like this:

String str1 = new StringBuilder("计算机").append("软件").toString();
System.out.println(str1.intern() == str1); //true

String str2 = new StringBuilder("ja").append("va").toString();
System.out.println(str2.intern() == str2); //false

String str3 = new StringBuilder("Str").append("ing").toString();
System.out.println(str3.intern() == str3); //true

I can understand why str1.intern() == str1 and str3.intern() == str3 are true, but I don't understand str2.intern() == str2. Why this is false?

My java version is: 1.8.0_73


回答1:


String.intern() returns a String in the string literal pool. However if the string already exists in the pool, it will return the existing String.

If you pick a new String, it should return the String you created, but if you use a String which happens to exist in the pool already you will get the existing String.

It is reasonable to assume that in this case "java" already exists in the pool so when you call intern() it returns a different object so == is false.

note: string.intern().equals(string) should always be true.




回答2:


The constant String "java" already exists in the Java constant pool, but you can verify that by changing

String str2 = new StringBuilder("ja").append("va").toString();
System.out.println(str2.intern()==str2);

to

String str2 = new StringBuilder("ja").append("va").toString();
System.out.println(str2.intern() == "java");

which will get the same constant and output

true

Alternatively, you could add "计算机软件" and "String" to the constant pool like

String a = "计算机软件";
String b = "String";
String str1 = new StringBuilder("计算机").append("软件").toString();
System.out.println(str1.intern() == str1);

String str3 = new StringBuilder("Str").append("ing").toString();
System.out.println(str3.intern() == str3);

Then you would get (consistent with your observations)

false
false


来源:https://stackoverflow.com/questions/36063388/why-does-the-string-intern-method-return-two-different-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!