Java 如何比较布尔值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22491853/
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-08-13 16:03:43  来源:igfitidea点击:

How to compare Boolean?

javaboolean

提问by ylun.ca

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

以此为例(摘自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?

如果.equals(false)用于检查 的值是否重要Boolean checker

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

我知道有是颇为相似。然而,显然这个问题涉及原始boolean而不是对象包装器,Boolean;因此,.equals()将不适用。

Also, should Booleanbe dealt differently than boolean?

此外,应该Boolean区别对待boolean

采纳答案by asteri

From your comments, it seems like you're looking for "best practices" for the use of the Booleanwrapper class. But there really aren'tany 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, i.e., storing a booleanin 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 NullPointerExceptions.

从您的评论来看,您似乎正在寻找使用Boolean包装类的“最佳实践” 。但是确实没有任何最佳实践,因为开始使用这个类是一个坏主意。使用对象包装器的唯一原因是在您绝对必须的情况下(例如使用泛型时,即,将 a 存储boolean在 aHashMap<String, Boolean>等中)。使用对象包装器没有任何好处,但也有很多坏处,最显着的是它使您对NullPointerExceptions敞开心扉。

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

'!' 有关系吗?用于代替 .equals() 用于布尔值?

Both techniques will be susceptible to a NullPointerException, so it doesn't matter in that regard. In the first scenario, the Booleanwill be unboxedinto its respective booleanvalue and compared as normal. In the second scenario, you are invoking a method from the Booleanclass, which is the following:

这两种技术都容易受到 a 的影响NullPointerException,因此在这方面无关紧要。在第一种情况下,Boolean将被拆箱为其各自的boolean值并正常进行比较。在第二种情况下,您正在从Boolean类中调用一个方法,如下所示

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?

如果使用 .equals(false) 来检查布尔检查器的值是否重要?

Per above, no.

如上所述,没有。

Secondary question: Should Boolean be dealt differently than boolean?

次要问题: Boolean 的处理方式应该与 boolean 不同吗?

If you absolutely mustuse the Booleanclass, always check for nullbefore performing any comparisons. e.g.,

如果您绝对必须使用Boolean该类,请始终null在执行任何比较之前进行检查。例如,

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-circuitsconditional evaluations. You can also use the ternary operator.

这将起作用,因为 Java 会短路条件评估。您还可以使用三元运算符。

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

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

但说真的……只要使用原始类型,除非您被迫不这样做。

回答by Luiggi Mendoza

As long as checkeris not null, you may use !checkeras posted. This is possible since Java 5, because this Booleanvariable will be autoboxed to the primivite booleanvalue.

只要checker不是null,您就可以!checker照常使用。从 Java 5 开始这是可能的,因为此Boolean变量将被自动装箱为原始boolean值。

回答by Migol

.equals(false)will be slower because you are calling a virtual method on an object rather than using faster syntax and rather unexpected by most of the programmers because code standards that are generally used don't really assume you should be doing that check via .equals(false)method.

.equals(false)会更慢,因为您在对象上调用虚拟方法而不是使用更快的语法,并且大多数程序员都出乎意料,因为通常使用的代码标准并没有真正假设您应该通过.equals(false)方法进行检查。

回答by ucsunil

Using direct conditions (like ==, !=, !condition) will have a slight performance improvement over the .equals(condition) as in one case you are calling the method from an object whereas direct comparisons are performed directly.

使用直接条件(如 ==、!=、!condition)将比 .equals(condition) 稍微提高性能,因为在一种情况下,您是从对象调用方法,而直接比较是直接执行的。

回答by ylun.ca

Regarding the performance of the direct operations and the method .equals(). The .equals()methods seems to be roughly 4 times slower than ==.

关于直接操作的性能和方法.equals()。这些.equals()方法似乎==.

I ran the following tests..

我进行了以下测试..

For the performance of ==:

对于性能==

public class BooleanPerfCheck {

    public static void main(String[] args) {
        long frameStart;
        long elapsedTime;

        boolean heyderr = false;

        frameStart = System.currentTimeMillis();

        for (int i = 0; i < 999999999; i++) {
            if (heyderr == false) {
            }
        }

        elapsedTime = System.currentTimeMillis() - frameStart;
        System.out.println(elapsedTime);
    }
}

and for the performance of .equals():

并为.equals()

public class BooleanPerfCheck {

    public static void main(String[] args) {
        long frameStart;
        long elapsedTime;

        Boolean heyderr = false;

        frameStart = System.currentTimeMillis();

        for (int i = 0; i < 999999999; i++) {
            if (heyderr.equals(false)) {
            }
        }

        elapsedTime = System.currentTimeMillis() - frameStart;
        System.out.println(elapsedTime);
    }
}

Total system time for ==was 1

系统的总时间==1

Total system time for .equals()varied from 3 - 5

总系统时间.equals()3 - 5

Thus, it is safe to say that .equals()hinders performance and that ==is better to use in most cases to compare Boolean.

因此,可以肯定地说,这会.equals()阻碍性能,并且==在大多数情况下最好使用 来比较Boolean

回答by yglodt

Try this:

尝试这个:

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

As additional benefit this is null-safe.

作为额外的好处,这是空安全的。

回答by CamelTM

As object?

作为对象?

equals

等于

public boolean equals(Object obj)

公共布尔等于(对象 obj)

Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.

当且仅当参数不为 null 并且是表示与此对象相同的布尔值的布尔对象时,才返回 true。

Overrides: equals in class Object

覆盖: 类 Object 中的 equals

Parameters: obj - the object to compare with.

参数: obj - 要比较的对象。

Returns: true if the Boolean objects represent the same value; false otherwise.

返回: 如果布尔对象表示相同的值,则为真;否则为假。

boolean a = true;
boolean b = false;

System.out.println("a.equals(b):" + ((Object)a).equals( ((Object)b) ));

Output: a.equals(b):false

输出:a.equals(b):false