如何检查两个布尔值是否相等?
How to check if two boolean values are equal?
我需要一个可以在 junit assertTrue()
方法中调用的方法,该方法比较两个布尔值以检查它们是否相等,return 一个布尔值。例如,像这样:
boolean isEqual = Boolean.equals(bool1, bool2);
如果它们不相等,应该 return 为 false,如果相等,则为 true。我检查了布尔值 class,但唯一接近的是 Boolean.compare()
,它 return 是一个 int 值,我不能使用它。
==
运算符使用布尔值。
boolean isEqual = (bool1 == bool2);
(括号是不必要的,但有助于阅读。)
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class BooleanEqualityTest {
@Test
public void equalBooleans() {
boolean boolVar1 = true;
boolean boolVar2 = true;
assertTrue(boolVar1 == boolVar2);
assertThat(boolVar1, is(equalTo(boolVar2)));
}
}
boolean isEqual = !(bool1 ^ bool2);
按位异或(异或)“^”是 Java 中的运算符,如果其操作数中的两个位不同,则提供答案“1”,如果两个位相同,则XOR 运算符给出结果“0”。
异或门是一种数字逻辑门,其功能是异或 (XOR) 门的逻辑补码。
我需要一个可以在 junit assertTrue()
方法中调用的方法,该方法比较两个布尔值以检查它们是否相等,return 一个布尔值。例如,像这样:
boolean isEqual = Boolean.equals(bool1, bool2);
如果它们不相等,应该 return 为 false,如果相等,则为 true。我检查了布尔值 class,但唯一接近的是 Boolean.compare()
,它 return 是一个 int 值,我不能使用它。
==
运算符使用布尔值。
boolean isEqual = (bool1 == bool2);
(括号是不必要的,但有助于阅读。)
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class BooleanEqualityTest {
@Test
public void equalBooleans() {
boolean boolVar1 = true;
boolean boolVar2 = true;
assertTrue(boolVar1 == boolVar2);
assertThat(boolVar1, is(equalTo(boolVar2)));
}
}
boolean isEqual = !(bool1 ^ bool2);
按位异或(异或)“^”是 Java 中的运算符,如果其操作数中的两个位不同,则提供答案“1”,如果两个位相同,则XOR 运算符给出结果“0”。
异或门是一种数字逻辑门,其功能是异或 (XOR) 门的逻辑补码。