简体   繁体   English

为什么布尔类中的重写equals(Object)方法不需要布尔值/布尔值作为参数

[英]Why doesn't the overridden equals(Object) method in the Boolean class require a boolean/Boolean as an argument

The following coding mistake is possible because the Boolean equals(Object) method doesn't require a boolean/Boolean argument: 由于布尔equals(Object)方法不需要布尔/布尔参数,因此可能出现以下编码错误:

private void foo() {
    Boolean isSomeConditionTrue = false;
    String doSomething = "YES";
    if(isSomeConditionTrue.equals(doSomething)) {
        // Do Something
    }
}

This code won't "do something" because the coder forgot to evaluate doSomething as a String in the predicate. 该代码不会“做某事”,因为编码器忘记了在谓词中将doSomething评估为String。 Why does the Boolean equals accept Object instead of boolean/Boolean as an argument? 为什么布尔等于接受对象而不是布尔/布尔作为参数?

Because equals() is defined in the Object class. 因为equals()是在Object类中定义的。

There is no possible signature it could have that would do what you want. 没有可能的签名可以满足您的要求。
(without making Object generic, which would defeat the purpose) (不使Object通用,这将违背目的)

This method overrides 该方法覆盖

Object.equals(Object)

and as such must accept all objects. 因此必须接受所有对象。

Similarly you can write 同样,你可以写

if (isSomeConditionTrue == doSomething) 

even though this can never be true either. 即使这也不可能是真的。

One way around this is to avoid using Wrappers which cannot be null anyway. 解决此问题的一种方法是避免使用Wrappers(无论如何都不能为null)。 ie Your code will only work if the Boolean is not null so don't use the wrapper, use the primitive. 即,您的代码仅在Boolean值不为null时有效,因此不要使用包装器,而应使用原语。

private void foo() {
    boolean isSomeConditionTrue = false;
    String doSomething = "YES";
    if(isSomeConditionTrue == doSomething) { // doesn't compile
        // Do Something
    }
}

Primitives are not only faster, they make it clearer that the value cannot be null and you can use the normal Java operations like == != > etc. 基元不仅更快,而且使值不能为null更加清晰,您可以使用== != >等常规Java操作。

equals() is a method on Object and the method contract requires that the parameter be an Object. equals()是Object上的方法,并且方法协定要求参数为Object。 The contract for equals states that if the object is the wrong type then it should return false. 等于合同规定,如果对象类型错误,则应返回false。

So you must convert doSomething into a Boolean first. 因此,您必须先将doSomething转换为布尔值。 Note that even Boolean.parseBoolean(String) only will return a Boolean.TRUE if the String word "true" ignoring case. 请注意,如果字符串单词“ true”忽略大小写,则即使Boolean.parseBoolean(String)也将仅返回Boolean.TRUE。 "yes" will not parse as TRUE. “是”将不会解析为TRUE。

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

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