【问题标题】:String handling: Usage of ==字符串处理:== 的用法
【发布时间】:2014-05-15 08:31:18
【问题描述】:

你能解释一下下面的代码吗:

我知道== 比较的是参考而不是值。 但我不清楚下面的代码到底发生了什么?

    public class StringEquals {
    public static void main(String args[])
    {

        String s1="AB";
        String s2="AB"+"C";
        String s3="A"+"BC";
        if(s1==s2)
        {
            System.out.println("s1 and s2 are equal");
        }
        else
        {
            System.out.println("s1 and s2 are notequal");
        }
        if(s2==s3)
        {
            System.out.println("s2 and s3 are equal");
        }
        else
        {
            System.out.println("s2 and s3 are notequal");
        }
        if(s1==s3)
        {
            System.out.println("s1 and s3 are equal");
        }
        else
        {
            System.out.println("s1 and s3 are notequal");
        }   
    }
    }

【问题讨论】:

  • 什么问题让你觉得自己不知道发生了什么?
  • 由于字符串实习,有时它们确实是同一个字符串;假设它仍然不安全
  • Stringcomparing(tutorialspoint.com/java/java_string_equals.htm)建议使用.equals方法

标签: java string compare


【解决方案1】:

在 Java 中,== 检查两个对象是否完全相同,有时它的行为与您的想法不同。

String s1 = new String("AB")
String s2 = new String("AB")

虽然s1s2内容相同,但是s1 == s2返回false。因为它们有不同的引用,但是s1 s2 具有相同的值所以s1.equals(s2) 返回true

【讨论】:

  • 值得注意的是,s2==s3 在这种情况下由于字符串实习而返回 true
【解决方案2】:

在我的系统上,代码打印

s1 and s2 are notequal
s2 and s3 are equal
s1 and s3 are notequal

如果你的问题是为什么,它与 Java 编译器如何处理字符串字面量有关。

通常,Java 会将所有对同一个字符串字面量的引用指向同一个对象,以提高效率。在s2s3 的情况下,编译器似乎已经意识到连接的结果是相同的字符串字面量,因此它分配引用s2s3 指向内存中的同一对象.这就是为什么这两个比较等于==

由于s1s2s3 的值不同,它将被分配不同的内存位置,因此引用不会与== 比较。

【讨论】:

    【解决方案3】:

    在您的代码中,您可能会输出System.out.println("s2 and s3 are equal");

    这是由于string interning。当字符串是编译时常量时,JVM 会将所有对相同字符串的引用设置为同一个对象。这是一种效率节省,Java 标准并没有强制 JVM 这样做,它只允许它这样做。你永远不应该依赖这种行为。

    因为在编译时已知"AB"+"C""A"+"BC" 都将评估为“ABC”,所以可以将s2s3 都设置为引用字符串池中的单个字符串。

    不用说,即使这在某些情况下有效,这也是一条危险的道路,应始终使用 string.equals(otherString) 比较字符串

    【讨论】:

      猜你喜欢
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多