【问题标题】:Android string compare is false [duplicate]Android字符串比较是假的[重复]
【发布时间】:2018-10-26 20:12:42
【问题描述】:

我有以下代码:

String week = this.getIntent().getStringExtra("weekNumber");
String correctWeek = Integer.toString(Calendar.WEEK_OF_YEAR);

if (week == correctWeek) {
    correct();
}

else incorrect();

都是“3”,但是比较结果是假的,不知道为什么:

哪里出错了?

【问题讨论】:

    标签: android string compare


    【解决方案1】:

    使用equals() 比较字符串的内容,而不是==

    == 将检查 objects 是否相同。

    String foo = "foo";
    
    if (foo == foo) {
        // same object, so true
    }
    
    String foo1 = "foo";
    String foo2 = "foo";
    
    if (foo1 == foo2) {
        // both are string literals set at compile time, so true
    }
    
    String foo1 = loadFoo1(); // imagine this returns "foo"
    String foo2 = loadFoo2(); // imagine this also returns "foo"
    
    if (foo1 == foo2) {
        // not the same object, and not string literals, so false
    }
    
    if (foo1.equals(foo2)) {
        // both strings hold "foo", so true
    }
    

    【讨论】:

      【解决方案2】:

      这两个字符串是独立的对象,“==”测试它的两个操作数是否是同一个对象。

      要比较字符串,请尝试 week.equals(correctWeek)

      【讨论】:

        【解决方案3】:

        “==”运算符用于参考比较。它检查两个对象是否指向相同的内存位置,当您比较两个不同的字符串对象时,它会在您的情况下返回 false

        出于您的目的,您应该使用 .equals(),它计算对象中值的比较。

        例子:

        String week =  new String("3"); 
        String correctWeek =  new String("3"); 
        System.out.println(week == correctWeek); 
        System.out.println(week.equals(correctWeek));
        

        将输出:

        false
        true
        

        【讨论】:

          猜你喜欢
          • 2013-04-15
          • 1970-01-01
          • 2010-11-03
          • 2011-10-07
          • 2012-09-26
          • 1970-01-01
          • 2012-04-14
          • 1970-01-01
          • 2018-07-09
          相关资源
          最近更新 更多