if语句比较java android中的字符串 [英] if statement comparing strings in java android

查看:40
本文介绍了if语句比较java android中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Java String.equals 与 ==

我正在尝试在 az DBOpenHelper extends SQLOpenHelper 类中编写一个方法.它应该评估数据库中是否有同名的条目.

I'm trying to write a method in az DBOpenHelper extends SQLOpenHelper class. It supposed to evaluate if there's an entry in the DB with the same name.

public boolean existsContact(Contact contact) {

    SQLiteDatabase db = this.getReadableDatabase();
    String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {

            String name = cursor.getString(1);
            String cname = contact.getName();
            if (name == cname) {

                cursor.close();
                db.close();
                return true;
            }

        } while (cursor.moveToNext());
    }

    db.close();

    return false;
}

这是 Contact 类的相关部分:

Here's the relevant part of Contact class:

 public class Contact {

    String _name;
    public String getName(){
        return this._name;
    }
    }

现在奇怪的是:

场景 A:if (name == cname) 其中 name = "foo"cname = "foo" 等于 false.Eclipse 调试器显示名称的 foo 和 cname 的 foo 具有不同的 ID.如之前在代码中看到的那样填充了两个变量.

Scenario A : if (name == cname) where name = "foo" and cname = "foo" equals false. Eclipse debugger show name's foo and cname's foo have different id's. both variables filled as seen before in code.

场景 B:if(name == cname) 变量的加载方式如下:

Scenario B: if(name == cname) where variabales are loaded like this:

String name = "foo";
String cname = "foo";
         statement equals true as it's supposed to.

场景 C:if("foo" == "foo") 等于 true...但是...调试器退出窗口.LogCat 显示调试器已连接,但 Eclipse 的 Debug 透视图中没有活动.断点不起作用.未显示任何主题.

Scenario C: if("foo" == "foo") equals true...BUT...debugger goes out the window. LogCat show debugger connected, but there's no activity in eclipse's Debug perspective. Breakpoints have no effect. No Threads shown.

推荐答案

在 Java 中,当在两个对象上使用 == 时,实际上并不是在比较字符串本身.您需要使用 .equals(String).

In java, when using == on two objects, you're not actually comparing the strings themselves. You'll need to use .equals(String).

== 实际上比较的是两个对象的引用,而不是它们的值.

== actually compares the two object's references, not their values.

string1.equals(String target) 根据字符串中的实际字符比较两个字符串.

string1.equals(String target) compares the two strings based off of the actual characters in the strings.

参见:http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html

这篇关于if语句比较java android中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆