【问题标题】:Would this be an example of short circuiting?这会是短路的例子吗?
【发布时间】:2013-12-18 23:13:49
【问题描述】:

如果我要求用户输入一个 int,并且需要在检查该索引处的数组以查看它是否不为空之前检查它是否在数组的索引范围内,这是否是“短电路”?因为如果数组大小只有 5 并且用户输入 15,那么我会得到一个 ArrayIndexOutOfBoundsException。但是如果我先检查输入的数字是否包含0-4,然后最后检查数组索引,则可以保证在0-4之间。所以我的问题是:这是“短路”的一个例子吗?我将在代码中重新表述我所说的......

import java.util.Scanner;

public Class Reservation{

    Customer[] customers = new Customer[5];
    Scanner input = new Scanner(System.in);
    //some code

    private void createReservation(){

        System.out.print("Enter Customer ID: ");
        int customerIndex;
        if(input.hasNextInt()){
            customerIndex = input.nextInt();
            //is the if-statement below a short-circuit
            if(customerIndex < 0 || customerIndex >= 5 || customers[customerIndex] == null){
                System.out.print("\nInvalid Customer ID, Aborting Reservation");
                return;
            }   
        }
        else{
            System.out.print("\nInvalid Customer ID, Aborting Reservation");
        }
    //the rest of the method
    }
}

【问题讨论】:

  • 短路一般特指&amp;&amp;||运算符在可以确定不需要计算右侧操作数时的行为。
  • short circuiting 上的维基百科条目
  • “短路”是一个高度依赖上下文的术语。最熟悉&amp;&amp;|| 运算符,也是编译器控制流优化和某些优化计算情况中的术语。一般来说,它是任何有“快速退出”或“绕过”的方案,当可以证明它是不必要的时,它可以避免某些操作。
  • Yes/no questions about an example are not a good fit for this site。除了最初的提问者之外,这些问题的答案对任何人都很少有用。该站点的目的是创建一个有用的高质量问题和答案的存储库。与其问“这是一个 X 的例子吗”,不如问“什么是 X”。是什么让您认为您的代码没有短路?

标签: java arrays indexoutofboundsexception short-circuiting program-flow


【解决方案1】:

是的,这是正确使用短路的有效示例:

if(customerIndex < 0 || customerIndex >= 5 || customers[customerIndex] == null)

此代码仅在|| 在获得true 后立即停止评估的假设下工作 - 否则,customers[customerIndex] 可能会通过无效索引到达,从而触发异常。

【讨论】:

  • 我现在明白了,谢谢 :) 当我有 15 个代表时,我会尽快投票
【解决方案2】:

是的,因为如果您的任何比较(从左到右)是true,则不需要评估右侧的其余比较。

另一个例子是:

if(node != null && node.value.equals("something"))

在这种情况下,如果node == null 发生短路,因为&amp;&amp; 需要两个true 值并且第一个是false,它不会评估第二个比较。

【讨论】:

  • 也谢谢你。当我得到足够的代表时,我也会投票给你的答案。
猜你喜欢
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 2019-02-13
  • 2011-02-11
  • 2011-04-12
  • 2011-03-10
相关资源
最近更新 更多