简体   繁体   English

数组索引超出范围未触发

[英]array index out of bounds not fired

public static void insertionSort(int[] data) {
    for (int i =0; i < data.length; i++) {
        int current = data[i];
        int j = i-1;
        while (j >=0 && data[j] >= current) {
            data[j+1] = data[j];
            j--;
        }
        data[j+1] = current;
    }
}

the line while (j >=0 && data[j] >= current) should throw array index of bounds when data[-1] for the first time. 该行while(j> = 0 && data [j]> = current)首次在data [-1]时应抛出边界数组索引。 I dont understand why it does not. 我不明白为什么没有。 Can some one please help Thank you Ashok Pappu 有人可以帮忙吗谢谢Ashok Pappu

Boolean expressions like these are never fully evaluated if the condition can be met earlier. 如果可以早些满足条件,则永远不会完全评估此类布尔表达式。

So...in your case since j >= 0 is false and false && ??? 所以...在您的情况下,因为j >= 0falsefalse && ??? will always be false the second part does not need to get evaluated. 永远为false ,第二部分不需要评估。 This is why data[-1] will never be called. 这就是为什么data[-1]永远不会被调用的原因。

You can use the same principle for null checks, eg 您可以对null检查使用相同的原理,例如

if (object != null && object.isSomething())

If while clause contains more, than 1 expression, splitted by && , they are executed one by one. 如果while子句包含多于1个由&&分割的表达式,它们将一一执行。 This is done to increase performance. 这样做是为了提高性能。 Ie at first in your code j >= 0 will checks. 即首先在您的代码中j >= 0将进行检查。 If j < 0 , it false. 如果j < 0 ,则为假。 So, cycle will be interrupted regardless of the 2nd expression. 因此,无论第二个表达式如何,循环都会中断。

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

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