Toggle a Boolean Variable in Java – 在Java中切换一个布尔变量

最后修改: 2022年 8月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Boolean is a fundamental data type in Java. Usually, it can have only two values, true or false.

布尔型是Java中的一个基本数据类型。通常,它只能有两个值,truefalse

In this tutorial, we’ll discuss how to toggle a given boolean variable.

在本教程中,我们将讨论如何切换一个给定的布尔变量。

2. Introduction to the Problem

2.对问题的介绍

This problem is pretty straightforward. Simply put, we want to invert the value of a boolean variable. For example, true becomes false after toggling.

这个问题很直接。简单地说,我们要反转一个布尔变量的值。例如,true在切换后变成false

However, we should note that there are two “different” boolean types in Java, the primitive boolean and the boxed Boolean. Therefore, the ideal toggle method should work for both types.

然而,我们应该注意到,Java中有两种 “不同的 “布尔类型,primitive booleanboxed Boolean因此,理想的切换方法应该对两种类型都有效。

In this tutorial, we’ll address how to implement such a method.

在本教程中,我们将讨论如何实现这样一种方法。

Also, for simplicity, we’ll use unit test assertions to verify if our implementations work as expected.

另外,为了简单起见,我们将使用单元测试断言来验证我们的实现是否按预期工作。

So next, let’s start with toggling a primitive boolean variable, as this is the base of our final toggle() method.

所以接下来,让我们从切换一个原始的boolean变量开始,因为这是我们最终的toggle()方法的基础。

3. Toggling a Primitive boolean Variable

3.切换一个原始的boolean变量

The most straightforward way to toggle a primitive boolean variable would be using the NOT operator(!).

切换原始boolean变量的最直接方法是使用NOT操作符(!)。

Let’s create a test to see how it works:

让我们创建一个测试,看看它是如何工作的。

boolean b = true;
b = !b;
assertFalse(b);

b = !b;
assertTrue(b);

If we run this test, it passes. Therefore, every time we perform the NOT operator on a boolean variable, its value will be inverted.

如果我们运行这个测试,它就会通过。因此,每次我们对boolean变量执行NOT操作时,它的值就会被倒置。

Alternatively, the XOR operator (^) can also invert a boolean. Before considering the implementation, let’s quickly understand how the XOR operator works.

另外,XOR运算符^)也可以反转一个布尔值。在考虑实现之前,让我们快速了解一下XOR运算符的工作原理。

Given two boolean variables b1 and b2, b1 ^ b2 is true only if b1 and b2 have different values, for example:

给定两个boolean变量b1b2b1 ^ b2只有在b1b2有不同值时才是true,例如。

  • true ^ true = false
  • false ^ false = false
  • true ^ false = true

Therefore, we can make use of XOR’s characteristics, performing b ^ true to invert b‘s value:

因此,我们可以利用XOR的特性,执行b ^ true来反转b的值

  • b = true -> b ^ true  becomes true ^ true = false
  • b = false -> b ^ true becomes false ^ true = true

Now that we understand the XOR’s logic, translating it into Java code isn’t a challenging task for us:

现在我们了解了XOR的逻辑,把它翻译成Java代码对我们来说并不是一个具有挑战性的任务。

boolean b = true;
b ^= true;
assertFalse(b);

b ^= true;
assertTrue(b);

Unsurprisingly, the test passes when we give it a run.

不出所料,当我们让它运行时,该测试通过了。

4. Creating the toggle() Method

4.创建toggle()方法

We’ve seen that a primitive boolean variable can only have two values: true and false. However, unlike the primitive boolean, the boxed Boolean variable can hold null.

我们已经看到,一个原始的boolean变量只能有两个值。truefalse。然而,与原始的boolean不同,盒式的Boolean变量可以持有null

Java automatically unboxes Boolean to boolean when we perform NOT or XOR operation on a Boolean variable. But if we don’t handle the null case properly, we’ll encounter NullPointerException:

当我们对一个Boolean变量进行NOT或XOR操作时,Java会自动将Boolean解压为boolean。但是如果我们没有正确处理null的情况,我们就会遇到NullPointerException

assertThatThrownBy(() -> {
    Boolean b = null;
    b = !b;
}).isInstanceOf(NullPointerException.class);

If we execute the test above, it passes. Unfortunately, this means that NullPointerException occurs when we perform !b.

如果我们执行上面的测试,它通过了。不幸的是,这意味着当我们执行!b时,会发生NullPointerException

So next, let’s create the null-safe toggle() method to work with both Boolean and boolean variables:

所以接下来,让我们创建一个空安全的toggle()方法,以便同时处理Booleanboolean变量。

static Boolean toggle(Boolean b) {
    if (b == null){
        return b;
    }
    return !b;
}

Here, we first perform a nullcheck and then use the NOT operator to invert the value. Of course, if we like, after the null-check, we could also use the XOR approach to invert b‘s value.

在这里,我们首先进行空检查,然后使用NOT运算符来反转值。当然,如果我们愿意,在空值检查之后,我们也可以使用XOR方法来反转b的值。

Finally, let’s create a test to verify if our toggle() method works for all cases:

最后,让我们创建一个测试来验证我们的toggle()方法是否对所有情况都有效。

// boxed Boolean
Boolean b = true;
b = ToggleBoolean.toggle(b);
assertFalse(b);

b = ToggleBoolean.toggle(b);
assertTrue(b);

b = null;
b = ToggleBoolean.toggle(b);
assertNull(b);

// primitive boolean
boolean bb = true;
bb = ToggleBoolean.toggle(bb);
assertFalse(bb);
bb = ToggleBoolean.toggle(bb);
assertTrue(bb);

As the test above shows, we tested the toggle() method with a Boolean variable and a boolean variable. Further, we’ve tested the scenario that the Boolean variable b=null.

如上面的测试所示,我们用一个Boolean变量和一个boolean变量来测试toggle()方法。此外,我们还测试了Boolean变量b=null的情况。

The test passes when we execute it. Therefore, our toggle() method works as expected.

当我们执行它时,测试通过了。因此,我们的toggle()方法按预期工作。

5. Conclusion

5.总结

In this article, we’ve learned how to build a null-safe method to toggle a given boolean/Boolean variable.

在这篇文章中,我们已经学会了如何建立一个空安全的方法来切换一个给定的boolean/Boolean变量。

As always, the code relating to this article is available over on GitHub.

一如既往,与本文有关的代码可在GitHub上获得over