简体   繁体   English

Java 中 String.intern 的奇怪之处

[英]weird thing about String.intern in Java

I am learning Java basic concept recently, when I tried some code samples about String.intern there was a weird thing happened.我最近在学习 Java 基本概念,当我尝试一些关于String.intern代码示例时,发生了一件奇怪的事情。 Code below:代码如下:

Snippet 1(normal):代码段 1(正常):

String str1 = new String("0") + new String("0");
str1.intern();
String str2 = "00";
assertTrue(str1 == str2); // pass
assertTrue(str1.equals(str2)); // pass

Snippet 2(weird):片段2(奇怪):

String str1 = new String("1") + new String("1");
str1.intern();
String str2 = "11";
assertTrue(str1 == str2); // fail; what happened???
assertTrue(str1.equals(str2)); // pass

Snippet 3(normal):代码段 3(正常):

String str1 = new String("2") + new String("2");
str1.intern();
String str2 = "22";
assertTrue(str1 == str2); // pass
assertTrue(str1.equals(str2)); // pass

So, I don't understand what happened about new String("1") , it's really really confused, I need your help, Thanks a lot!所以,我不明白new String("1")发生了什么,真的很困惑,我需要你的帮助,非常感谢!

Any string which is already in the string literal pool will already have an object and will not be added when you call str1.intern() as it is already there.任何已经在字符串文字池中的字符串都已经有一个对象,并且在调用str1.intern()时不会被添加,因为它已经存在了。

On starting, the JVM creates thousands of objects and has many objects already in the String literal pool by the time main() is called.开始时,JVM 创建了数千个对象,并且在调用 main() 时字符串文字池中已经有许多对象。

Which strings are already in the pool depends on what code was run before your code.池中已经存在哪些字符串取决于在您的代码之前运行的代码。

System.out.println("Strings already in the literal pool");
for (char ch = ' '; ch < 127; ch++) {
    String s = Character.toString(ch);
    System.out.println(s + " " + (s != s.intern()));
}

prints印刷

Strings already in the literal pool
  true
! false
" true
# false
$ false
% true
& true
' true
( false
) false
* true
+ false
, true
- true
. true
/ true
0 false
1 false
2 false
3 false
4 false
5 false
6 false
7 false
8 false
9 false
: true
; false
< true
= false
> false
? false
@ true
A false
B false
C false
D false
E false
F false
G false
H false
I true
J false
K false
L false
M false
N false
O false
P false
Q false
R false
S false
T false
U true
V false
W false
X false
Y false
Z true
[ true
\ false
] true
^ false
_ true
` false
a false
b false
c false
d false
e false
f false
g false
h false
i false
j false
k false
l false
m false
n false
o false
p false
q false
r false
s false
t false
u false
v false
w false
x false
y false
z false
{ false
| true
} false
~ false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM