原因
在Java中,运算符&&=
和||=
是不可用的,因为对于大多数开发人员来说,这些运算符具有以下特点:
&&=
的示例
如果Java允许使用&&=
运算符,则以下代码:
bool isOk = true; //becomes false when at least a function returns false
isOK &&= f1();
isOK &&= f2(); //we may expect f2() is called whatever the f1() returned value
等同于以下代码:
bool isOk = true;
if (isOK) isOk = f1();
if (isOK) isOk = f2(); //f2() is called only when f1() returns true
这段代码容易出现错误,因为许多开发人员会认为 f2()
总是会被调用,无论 f1()
返回什么值。它就像 bool isOk = f1() && f2();
,只有当 f1()
返回 true
时才会调用 f2()
。
如果开发人员希望只有在 f1()
返回 true
时才调用 f2()
,那么上面的第二个代码就更安全一些。
否则,使用 &=
就足够了,因为开发人员希望f2()
总是被调用:
同样的例子,但是针对 &=
bool isOk = true;
isOK &= f1();
isOK &= f2(); //f2() always called whatever the f1() returned value
此外,JVM应该将以上代码运行为以下代码:
bool isOk = true;
if (!f1()) isOk = false;
if (!f2()) isOk = false; //f2() always called
比较&&
和&
的结果
当应用于布尔值时,运算符&&
和&
的结果是否相同?
让我们使用以下Java代码进行检查:
public class qalcdo {
public static void main (String[] args) {
test (true, true);
test (true, false);
test (false, false);
test (false, true);
}
private static void test (boolean a, boolean b) {
System.out.println (counter++ + ") a=" + a + " and b=" + b);
System.out.println ("a && b = " + (a && b));
System.out.println ("a & b = " + (a & b));
System.out.println ("======================");
}
private static int counter = 1;
}
输出:
1) a=true and b=true
a && b = true
a & b = true
======================
2) a=true and b=false
a && b = false
a & b = false
======================
3) a=false and b=false
a && b = false
a & b = false
======================
4) a=false and b=true
a && b = false
a & b = false
======================
因此,对于布尔值,是的,我们可以用&
来替换&&
;-)
因此,最好使用&=
而不是&&=
。
对于||=
也是一样的
与&&=
相同的原因:
运算符|=
比||=
更不容易出错。
如果开发人员希望在f1()
返回true
时不调用f2()
,那么我建议使用以下替代方案:
bool isOk = f1() || f2() || f3() || f4();
或者:
// here the following comments are not required
// (the code is enough understandable)
bool isOk = false;
if (!isOK) isOk = f1();
if (!isOK) isOk = f2(); //f2() is not called when f1() returns false
if (!isOK) isOk = f3(); //f3() is not called when f1() or f2() return false
if (!isOK) isOk = f4(); //f4() is not called when ...