例如:当我调用 intern() 方法后用 == 运算符比较两个字符串时,它返回 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。
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。
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**
为什么第三个输出为假? 请帮忙。
最佳答案
来自String.intern()
文档:
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.
因此 "ja".concat("va").intern()
返回池中已存在的字符串“java”的实例(因为该字符串已存在于很多地方在 JVM 中并且显然是被实习的)。在您的代码中,a1
指向预先存在的实习实例,a
指向您刚刚构建的实例。
并且"Wahab".concat("Shaikh").intern()
返回您刚刚创建的字符串“WahabShaikh”的实例。
关于java - 比较两个字符串 s = "ja".concat ("va"); s1=s.intern();与 == 运算符返回 false。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45575811/