Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

java - Why are the results of of str == str.intern() for these strings different?

public static void main(String[] args) {
    String str1 = new StringBuilder("计算机").append("软件").toString();
    System.out.println(str1.intern() == str1);
    String str2 = new StringBuffer("ja").append("va").toString();
    System.out.println(str2.intern() == str2);
}

Results:

 true
 false   

First one prints true, and the second prints false. Why are the results different?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The difference in behavior is unrelated to the differences between StringBuilder and StringBuffer.

The javadoc of String#intern() states that it returns

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

The String created from

String str2 = new StringBuffer("ja").append("va").toString();

is a brand new String that does not belong to the pool.

For

str2.intern() == str2

to return false, the intern() call must have returned a different reference value, ie. the String "java" was already in the pool.

In the first comparison, the String "计算机软件" was not in the string pool prior to the call to intern(). intern() therefore returned the same reference as the one stored in str2. The reference equality str2 == str2 therefore returns true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...