为什么 String.intern() 方法返回两个不同的结果? [英] Why does the String.intern() method return two different results?

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

问题描述

我有这样的代码:

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

我能理解为什么 str1.intern() == str1str3.intern() == str3 是正确的,但我不理解 str2.intern() == str2.为什么这是假的?

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?

我的java版本是:1.8.0_73

My java version is: 1.8.0_73

推荐答案

String.intern() 返回字符串文字池中的字符串.但是,如果字符串已存在于池中,它将返回现有的字符串.

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.

假设在这种情况下 "java" 已经存在于池中是合理的,所以当你调用 intern() 时它返回一个不同的对象,所以 == 是假的.

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.

注意:string.intern().equals(string) 应该始终为真.

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

这篇关于为什么 String.intern() 方法返回两个不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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