String.intern()究竟是如何工作的

时间:2013-07-08 14:10:26

标签: java string char

我想知道为什么在以下代码中:

   String args0 = args[0];
   String args1 = args[1];
   args0.intern();
   args1.intern();

   if (args0==args1){
      System.out.println("Success");
   } else {
      System.out.println("Failure");
   }

通过作为行命令参数传递2个相同的字符串,它返回failure

提前致谢。

6 个答案:

答案 0 :(得分:4)

由于String不可变,您需要分配实例intern()返回,以使变量引用实例化实例,以便==比较返回{ {1}}。

true

在您的示例String args0 = args[0]; String args1 = args[1]; args0 = args0.intern(); args1 = args1.intern(); if (args0==args1){ System.out.println("Success"); } else { System.out.println("Failure"); } 中,args0仍然引用数组中的原始不同实例。

答案 1 :(得分:1)

你必须这样做:

if (args0.intern() == args1.intern()){
    System.out.println("Success");
}

答案 2 :(得分:0)

字符串不可变

.intern()返回实习池中的(可能)不同的 String实例。

你扔掉了这个实例。

答案 3 :(得分:0)

Java自动实习字符串文字。这意味着在许多情况下,==运算符似乎适用于字符串,就像它对整数或其他原始值一样。

由于对于字符串文字是自动的,因此intern()方法将用于使用new String()构造的字符串。

您也可以参考此示例:

public class Test
{
   public static void main(String args[]){
      String Str1 = new String("Welcome to Tutorialspoint.com");
      String Str2 = new String("WELCOME TO SUTORIALSPOINT.COM");

      System.out.print("Canonical representation:" );
      System.out.println(Str1.intern());

      System.out.print("Canonical representation:" );
      System.out.println(Str2.intern());
   }
}

答案 4 :(得分:0)

(我假设args0args1持有具有相同值的字符串)

  1. args0.intern()将检查字符串池是否已包含与args0中的字符串具有相同值的字符串。
  2. 如果池包含此类String,则将返回对它的引用,如果不是,则将创建与args0具有相同值的新String,将其放置在池引用中返回。
  3. args0.intern();
    args1.intern();
    

    args0args1仍然保留命令行中使用的字符串,因此它们与池中的字符串不同。

    要改变它,请尝试

    args0 = args0.intern();
    args1 = args1.intern();
    

    现在args0 = args0.intern();会将args0中的“put”字符串放在池更新args0中以保存该字符串。 args1 = args1.intern();实习生将看到该池包含相同的字符串(之前放置args0.intern()),因此只返回对它的引用并将其存储在args1下。

    现在if(args0 == args1)应为true,因为两个引用都是相同的String对象。

答案 5 :(得分:0)

字符串是不可变的,其方法总是返回已更改的String

 args0 = args0.intern();
 args1 = args1.intern();
相关问题