问题描述
例如:当我在调用 intern() 方法后使用 == 运算符比较两个字符串时,它返回 true.
For Eg: When I compare two strings with == operator after I call intern() method it returns true.
String name = "Wahab"; // in string literal pool
String fullName = new String("Wahab"); // new string in heap
String f = fullName.intern(); // pushing into string literal pool
System.out.print(name == f); // **true**
使用 Concat 并调用 intern(),== 运算符返回 true.
Using Concat and invoke intern(), == operator returns true.
String name = "Wahab".concat("Shaikh"); // concat with new string
String fullName = name.intern(); // invoke intern to push into string literal pool
System.out.print(name == fullName); // **true**
使用较少的字符,连接并调用 intern() 然后返回 false.
Having fewer chars, concatenate and invoke intern() then it returns false.
String a = "ja".concat("va"); // concat with fewer characters
String a1 = a.intern(); // push into literal pool and assign to new variable
System.out.print(a == a1); // **false**
为什么第三个输出是假的?请帮忙.
Why is the third output false? Please help.
推荐答案
来自 String.intern()
文档:
From String.intern()
doc:
当调用intern方法时:
- 如果池中已经包含由 equals(Object) 方法确定的等于此 String 对象的字符串,则返回池中的字符串.
- 否则,将此 String 对象添加到池中并返回对此 String 对象的引用.
所以 "ja".concat("va").intern()
返回池中已经存在的 String "java" 的实例(因为这个字符串已经存在很多地方了在 JVM 中并且显然是实习的).在您的代码中,a1
指向预先存在的内部实例,a
指向您刚刚构建的实例.
So "ja".concat("va").intern()
returns the instance of String "java" that already exists in the pool (because that string already exists in a lot of places in the JVM and is apparently interned). In your code, a1
points to the pre-existing interned instance, and a
points to the instance you just built.
并且 "Wahab".concat("Shaikh").intern()
返回您刚刚创建的 String "WahabShaikh" 的实例.
And "Wahab".concat("Shaikh").intern()
returns the instance of String "WahabShaikh" that you just created.
这篇关于比较两个字符串 s = "ja".concat("va");和 s1=s.intern();with == 运算符返回 false.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!