简体   繁体   English

Java 如何在 while 循环条件下处理越界数组索引?

[英]How does Java handle an out-of-bound array index in a while-loop condition?

I'm following a tutorial for a two-pointer implementation (solution for 3Sum essentially) and I'm confused about the second while-loop in this search method:我正在关注双指针实现的教程(本质上是 3Sum 的解决方案),我对这种搜索方法中的第二个 while 循环感到困惑:

  private static void searchPair(int[] arr, int targetSum, int left, List<List<Integer>> triplets) {

    int right = arr.length - 1;
    
    while (left < right) {
        int currentSum = arr[left] + arr[right];

        if (currentSum == targetSum) { // found the triplet
            triplets.add(Arrays.asList(-targetSum, arr[left], arr[right]));
            left++;
            right--;

            while (left < right && arr[left] == arr[left - 1])
              left++; // skip same element to avoid duplicate triplets
            while (left < right && arr[right] == arr[right + 1])
              right--; // skip same element to avoid duplicate triplets
      
    } else if (targetSum > currentSum)
        left++; // we need a pair with a bigger sum
      else
        right--; // we need a pair with a smaller sum
  }
}

while (left < right && arr[right] == arr[right + 1]) while (left < right && arr[right] == arr[right + 1])

Won't this be an out of bounds exception since right is the last index, so right + 1 will be out of bounds?这不是越界异常,因为right是最后一个索引,所以right + 1会越界吗? But the code runs just fine so I'm confused.但是代码运行得很好,所以我很困惑。 How does Java handle this case? Java如何处理这种情况?

Java handles the && in order. Java 按顺序处理 &&。 Meaning that if left < right fails (ie it's the last element), then the second part of the conditional is not evaluated at all.这意味着如果 left < right 失败(即它是最后一个元素),则根本不评估条件的第二部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM