How to compare Boolean?

Take this for example (excerpt from Java regex checker not working):

while(!checker) {
    matcher = pattern.matcher(number);
    if(matcher.find())
        checker = true;
    else
        year++;
}

Would it matter if .equals(false) was used to check for the value of the Boolean checker ?

I know that there is this which is rather similar. However, obviously the question deals with primitive boolean and not the object wrapper, Boolean ; thus, .equals() would not be applicable.

Also, should Boolean be dealt differently than boolean ?


From your comments, it seems like you're looking for "best practices" for the use of the Boolean wrapper class. But there really aren't any best practices, because it's a bad idea to use this class to begin with. The only reason to use the object wrapper is in cases where you absolutely must (such as when using Generics, ie, storing a boolean in a HashMap<String, Boolean> or the like). Using the object wrapper has no upsides and a lot of downsides, most notably that it opens you up to NullPointerException s.

Does it matter if '!' is used instead of .equals() for Boolean?

Both techniques will be susceptible to a NullPointerException , so it doesn't matter in that regard. In the first scenario, the Boolean will be unboxed into its respective boolean value and compared as normal. In the second scenario, you are invoking a method from the Boolean class, which is the following:

public boolean equals(Object obj) {
    if (obj instanceof Boolean) {
        return value == ((Boolean)obj).booleanValue();
    }
    return false;
}

Either way, the results are the same.

Would it matter if .equals(false) was used to check for the value of the Boolean checker?

Per above, no.

Secondary question: Should Boolean be dealt differently than boolean?

If you absolutely must use the Boolean class, always check for null before performing any comparisons. eg,

Map<String, Boolean> map = new HashMap<String, Boolean>();
//...stuff to populate the Map
Boolean value = map.get("someKey");
if(value != null && value) {
    //do stuff
}

This will work because Java short-circuits conditional evaluations. You can also use the ternary operator.

boolean easyToUseValue = value != null ? value : false;

But seriously... just use the primitive type, unless you're forced not to.


Try this:

if (Boolean.TRUE.equals(yourValue)) { ... }

As additional benefit this is null-safe.


As long as checker is not null , you may use !checker as posted. This is possible since Java 5, because this Boolean variable will be autoboxed to the primivite boolean value.

链接地址: http://www.djcxy.com/p/91836.html

上一篇: 为什么Java不允许在Enum中重写equals(Object)?

下一篇: 如何比较布尔?