为什么这些字符串的str == str.intern()结果不同? [英] Why are the results of of str == str.intern() for these strings different?

查看:304
本文介绍了为什么这些字符串的str == str.intern()结果不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
}

结果:

 true
 false   

第一个打印 true ,第二个打印 false 。为什么结果不同?

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

推荐答案

行为上的差异与 StringBuilder之间的差异无关 StringBuffer

String #intern() 表明它返回

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


调用实习方法时,如果池已包含等于此<$ c的
字符串$ c> String 由 equals(Object)
方法确定的对象,然后返回池中的字符串
。否则,此
String 对象将添加到池中,对此 String的引用
对象被返回。

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.

String 已创建from

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

是一个全新的字符串属于游泳池。

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

对于

str2.intern() == str2

返回 false intern()调用必须返回不同的参考值,即。 字符串 java已经在池中

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

在第一次比较中, String 计算机软件不在调用的字符串池之前 intern() intern()因此返回与 str2 中存储的引用相同的引用。引用相等 str2 == str2 因此返回 true

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.

这篇关于为什么这些字符串的str == str.intern()结果不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆