简体   繁体   中英

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:

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. Why does the Boolean equals accept Object instead of boolean/Boolean as an argument?

Because equals() is defined in the Object class.

There is no possible signature it could have that would do what you want.
(without making Object generic, which would defeat the purpose)

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. ie Your code will only work if the Boolean is not null so don't use the wrapper, use the primitive.

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.

equals() is a method on Object and the method contract requires that the parameter be an Object. The contract for equals states that if the object is the wrong type then it should return false.

So you must convert doSomething into a Boolean first. Note that even Boolean.parseBoolean(String) only will return a Boolean.TRUE if the String word "true" ignoring case. "yes" will not parse as TRUE.

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.

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