I'm currently working on an android application that uses a subclass of SimpleListAdapter to bind a ListActivity. The list that the Adapter binds to is of type List<HashMap<String, Object>>
.
I have to following If statement in the list Adapter...
if (dataRow.get("HasLineup1").toString()) == "0")
This never evaluates to true
for me, even when the Eclipse debugger says that dataRow.get("HasLineup1").toString()
is equal to "0"
in the inspection window.
The list of data is populated from an XML source with the line
Game.put("HasLineup1", attributes.getNamedItem("home_lineup").getNodeValue());
I managed to work around the issue by changing the If statement to
if (Integer.parseInt(dataRow.get("HasLineup1").toString()) == 0)
Can someone explain to me why the first If statement I used wasn't working? Java isn't my native language, but I can't for the life of me figure out what I'm doing wrong based on my .Net background.
The ==
operator compares the instance memory location for non-primitive types therefore this fails unless the two sides of the operand are the same instance. Whenever dealing with non-primitive types, use equals
instead of ==
.
如果您使用的是string
,则应使用equals
方法。
if (dataRow.get("HasLineup1").toString())equals("0"))
The equality operator ==
will do the following, based on what you're comparing:
int
, char
, ...): check if their values are the same. In other words, for non-primitives ==
doesn't imply semantics. You'll want the equals
method for that. It's defined on Object
so it'll always be available. But its semantics are determine by how (and if) a specific class decides to override this method.
For String, it's a character-by-character comparison with the argument of the method.
Here is a link with references about the differences between == and equals. == compares references, while equals() compares the values.
http://leepoint.net/notes-java/data/expressions/22compareobjects.html
Use
if (dataRow.get("HasLineup1").toString()).equals("0"))
==
(double equals) only compares the objects to see if they point to the same place in memory. the equals
method actually compares the characters in the two strings to one another.
在使用“ ==”之前,必须在两个字符串上都使用方法“ equals”或调用.internal()。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.