我只是想知道为什么我们通常在两个布尔值之间使用逻辑OR ||,而不是按位或|,尽管它们都工作得很好。

我的意思是,看看下面这些:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

我们可以用|代替||吗?&和&&也是一样。


当前回答

非短路是有用的。有时你想确保两个表达式都有值。例如,假设您有一个从两个单独的列表中删除对象的方法。你可能想这样做:

class foo {

    ArrayList<Bar> list1 = new ArrayList<Bar>();
    ArrayList<Bar> list2 = new ArrayList<Bar>();

    //Returns true if bar is removed from both lists, otherwise false.
    boolean removeBar(Bar bar) {
        return (list1.remove(bar) & list2.remove(bar));
    }
}

如果您的方法改为使用条件操作数,如果第一个列表返回false,则它将无法从第二个列表中删除对象。

//Fails to execute the second remove if the first returns false.
boolean removeBar(Bar bar) {
    return (list1.remove(bar) && list2.remove(bar));
}

它并不是特别有用,并且(与大多数编程任务一样)您可以通过其他方法实现它。但这是位操作数的一个用例。

其他回答

它们之间的基本区别是|首先将值转换为二进制,然后执行按位或操作。同时,||不将数据转换为二进制,只是在其原始状态上执行or表达式。

int two = -2; int four = -4;
result = two | four; // bitwise OR example

System.out.println(Integer.toBinaryString(two));
System.out.println(Integer.toBinaryString(four));
System.out.println(Integer.toBinaryString(result));

Output:
11111111111111111111111111111110
11111111111111111111111111111100
11111111111111111111111111111110

阅读更多信息:http://javarevisited.blogspot.com/2015/01/difference-between-bitwsie-and-logical.html#ixzz45PCxdQhk

| =位或,|| =逻辑或

|是位运算符:||是短路运算符——当一个元素为假时,它将不检查其他元素。

 if(something || someotherthing)
 if(something | someotherthing)

如果某个值为TRUE, ||将不会计算另一个值,而|可以。如果If语句中的变量实际上是函数调用,那么使用||可能会节省大量性能。

非短路是有用的。有时你想确保两个表达式都有值。例如,假设您有一个从两个单独的列表中删除对象的方法。你可能想这样做:

class foo {

    ArrayList<Bar> list1 = new ArrayList<Bar>();
    ArrayList<Bar> list2 = new ArrayList<Bar>();

    //Returns true if bar is removed from both lists, otherwise false.
    boolean removeBar(Bar bar) {
        return (list1.remove(bar) & list2.remove(bar));
    }
}

如果您的方法改为使用条件操作数,如果第一个列表返回false,则它将无法从第二个列表中删除对象。

//Fails to execute the second remove if the first returns false.
boolean removeBar(Bar bar) {
    return (list1.remove(bar) && list2.remove(bar));
}

它并不是特别有用,并且(与大多数编程任务一样)您可以通过其他方法实现它。但这是位操作数的一个用例。

操作符||和&&被称为条件操作符,而|和&被称为位操作符。它们有不同的用途。

条件操作符仅适用于在左侧和右侧都静态求值为布尔值的表达式。

位操作符适用于任何数字操作数。

如果希望执行逻辑比较,则应该使用条件操作符,因为您将向代码添加某种类型安全。