字符串在 Android 上的 Java 中似乎并不相等,即使它们打印相同

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2704956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:25:57  来源:igfitidea点击:

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

javaandroidstringequalsequality

提问by robintw

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

我有一个问题,我很困惑。我的 android 应用程序中有以下几行代码:

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".

当我查看第一个 println 语句的输出时,它在 LogCat 中显示为“开始”(显然没有引号)。但是当 if 语句执行时,它会转到 else 语句并打印“不,它没有”。

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.

我想知道节点的名称中是否可能包含某种非打印字符,所以我检查了来自 getNodeName() 的字符串的长度,它有 5 个字符长,如您所料。

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

有没有人知道这里发生了什么?

回答by Bill the Lizard

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

使用 String 的equals方法比较字符串。该==运营商将只比较对象的引用。

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

回答by Xavier Ho

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

使用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.

在 Java 中,新手遇到的最常见的错误之一是使用==比较字符串。你必须记住,==比较对象标识(想想内存地址),而不是内容

回答by NG.

You need to use .equals

你需要使用 .equals

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