java - 比较两个字符串 s = "ja".concat ("va"); s1=s.intern();与 == 运算符返回 false。为什么?

标签 java string string-comparison

  1. 例如:当我调用 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**
    
  2. 使用 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**
    
  3. 字符数较少,连接并调用 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/

相关文章:

java - 将应用程序移动到其他框架,然后返回到上一个

c - GLib:哈希表无法正确找到值

python - 如何删除这个特殊字符?

java - 用大写字母分割字符串

java - 如何将 ArrayList 中的元素与特定字符串进行比较?

c++ - Visual Studio 中 stricmp 和 _stricmp 的区别?

c# - 字符串内容相同但长度不同

java - java中的构造函数

java - 无法在单元测试的 Before 和 After 方法中启动/停止 Spark

java - 如何从 Java Swing 应用程序运行 OSX 字符查看器