Strings don't seem to be equal in Java on Android, even though they print the same

两盒软妹~` 提交于 2019-11-29 17:16:05

问题


I've got a problem that I'm rather confused about. I have the following lines of code in my android application:

System.out.println(CurrentNode.getNodeName().toString());
if (CurrentNode.getNodeName().toString() == "start") {
    System.out.println("Yes it does!");
} else {
    System.out.println("No it doesnt");
}

When I look at the output of the first println statement it shows up in LogCat as "start" (without the quotes obviously). But then when the if statement executes it goes to the else statement and prints "No it doesn't".

I wondered if the name of the node might have some kind of non-printing character in it, so I've checked the length of the string coming from getNodeName() and it is 5 characters long, as you would expect.

Has anyone got any idea what's going on here?


回答1:


Use String's equals method to compare Strings. The == operator will just compare object references.

if ( CurrentNode.getNodeName().toString().equals("start") ) {
   ...



回答2:


Use CurrentNode.getNodeName().toString().equals("start").

In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object identity (Think memory addresses), not the content.




回答3:


You need to use .equals

if ("start".equals(CurrentNode.getNodeName().toString()) { ... }


来源:https://stackoverflow.com/questions/2704956/strings-dont-seem-to-be-equal-in-java-on-android-even-though-they-print-the-sa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!