简体   繁体   English

Java Object 相等方法和布尔值

[英]Java Object equal method and Boolean value

I have the following code snippet我有以下代码片段

  format(Object obj) {
    if(obj.equals("false")) {
      buffer.append("No");
    } else {
      buffer.append("Yes");
    }
  }

When debugging, I verify that the value of obj variable is a Boolean object with the value "false", but the if clause always go to the Yes instruction.调试时,我验证obj变量的值是一个值为“false”的布尔对象,但是if子句总是转到Yes指令。 Can you help me understand why?你能帮我理解为什么吗?

When you run obj.equals("false") you're trying to compare obj , a Boolean , with "false" , which is a String .当您运行obj.equals("false")您试图将obj (一个Boolean )与"false" (一个String

So you can try to first convert the Boolean to a string:因此,您可以尝试先将Boolean转换为字符串:

if(obj.toString().equals("false")){
    buffer.append("No");
} else {
    buffer.append("Yes");
}

Or, even better, as suggested by @Nexevis, you can compare obj directly to a Boolean :或者,更好的是,正如@Nexevis 所建议的那样,您可以将obj直接与Boolean进行比较:

if(obj.equals(false)){
    buffer.append("No");
} else {
    buffer.append("Yes");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM