if语句比较java中的字符串android [英] if statement comparing strings in java android
问题描述
可能重复:
Java String.equals vs. ==
我试图写一个方法在az DBOpenHelper中扩展SQLOpenHelper类。
它应该评估DB中是否有一个名称相同的条目。
public boolean existsContact(Contact contact){
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery =SELECT * FROM+ TABLE_CONTACTS;
游标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();
返回true;
}
} while(cursor.moveToNext());
}
db.close();
返回false;
}
以下是联系电话课程的相关部分:
public class Contact {
String _name;
public String getName(){
return this._name;
}
}
现在这里有一个奇怪的事情:
$ a code> if c>和 cname =foo
等于false。 Eclipse调试器显示名称的foo和cname的foo有不同的id。
这两个变量都在代码中被看见。
方案B: if(name == cname)
其中变量加载如下:
String name =foo;
String cname =foo;
语句等于true,因为它应该是。
方案C: if(foo==foo)
等于true ...但是...调试器走出窗口。 LogCat显示调试器已连接,但在eclipse的Debug透视图中没有任何活动。断点没有效果。没有线程显示。
在java中,当使用 ==
两个对象,你并不是真的比较字符串本身。您需要使用 .equals(String)
。
==
实际上比较了两个对象的引用,而不是它们的值。
string1.equals(String target)
根据字符串中的实际字符比较两个字符串。
请参阅: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html
Possible Duplicate:
Java String.equals versus ==
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;
}
Here's the relevant part of Contact class:
public class Contact {
String _name;
public String getName(){
return this._name;
}
}
Now here's the strange thing:
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.
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.
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.
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)
compares the two strings based off of the actual characters in the strings.
See: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html
这篇关于if语句比较java中的字符串android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!