什么是短路以及在 Java 编程时如何使用它? [英] What is short circuiting and how is it used when programming in Java?

查看:28
本文介绍了什么是短路以及在 Java 编程时如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
在布尔结果已知后java是否评估剩余条件
为什么我们通常使用||不是|,有什么区别?

Possible Duplicate:
Does java evaluate remaining conditions after boolean result is known
Why do we usually use || not |, what is the difference?

前几天我错过了我的课堂讲座,我想知道是否有人可以解释什么是短路,也许可以举一个在简单 Java 程序中使用它的例子.感谢您的帮助!

I missed my class lecture the other day and I was wondering if anyone could give an explanation what short circuiting is and maybe an example of it being used in a simple Java program. Thanks for your help!

推荐答案

短路是在表达式的结果确定后立即停止求值.例如:

Short-circuiting is where an expression is stopped being evaluated as soon as its outcome is determined. So for instance:

if (a == b || c == d || e == f) {
    // Do something
}

如果 a == b 为真,则 c == de == f 不会被评估,因为表达式的结果已经确定.如果 a == b 为假,则对 c == d 求值;如果它是真的,那么 e == f 永远不会被评估.这似乎没有任何区别,但请考虑:

If a == b is true, then c == d and e == f are never evaluated at all, because the expression's outcome has already been determined. if a == b is false, then c == d is evaluated; if it's true, then e == f is never evaluated. This may not seem to make any difference, but consider:

if (foo() || bar() || baz()) {
    // Do something
}

如果 foo() 返回 true,则 barbaz 不会被调用,因为表达式的结果已经确定.因此,如果 barbaz 有一些其他效果,而不仅仅是返回某些东西(副作用),这些效果就永远不会发生.

If foo() returns true, then bar and baz are never called, because the expression's outcome has already been determined. So if bar or baz has some other effect than just returning something (a side effect), those effects never occur.

短路的一个很好的例子与对象引用有关:

One great example of short-circuiting relates to object references:

if (a != null && a.getFoo() != 42) {
    // Do something
}

如果 anull

a.getFoo() 通常会抛出 NullPointerException,但因为表达式短路,如果 a != nullfalsea.getFoo() 部分永远不会发生,所以我们不会得到例外.

a.getFoo() would normally throw a NullPointerException if a were null, but because the expression short-circuits, if a != null is false, the a.getFoo() part never happens, so we don't get an exception.

请注意,并非所有表达式都是短路的.||&& 运算符是短路的,但 |& 不是,也不是 */;事实上,大多数运营商都不是.

Note that not all expressions are short-circuited. The || and && operators are short-circuited, but | and & are not, nor are * or /; in fact most operators are not.

这篇关于什么是短路以及在 Java 编程时如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆