java if里字符串的比较,if语句比较java中的字符串android

在Java中,直接使用'=='比较两个字符串对象时,实际上是对比它们的内存引用,而非字符串内容。博客作者遇到了一个问题,当尝试检查数据库中是否存在相同名字的联系人时,发现'=='比较返回了错误的结果。通过调试,作者发现只有在硬编码字符串时'=='才返回预期的true。正确的做法是使用'.equals()'方法进行字符串内容的比较。这个博客强调了在Java中正确比较字符串的重要性。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值