我無法找到這個問題的答案。我工作的一個插入排序方法,它不會正確執行:條件順序在while循環中與多個條件有關嗎?
public static <T extends Comparable<? super T>> void insertionSort(T[] array) {
int length = array.length;
T temp;
for (int i = 1; i < length; i++) { //start of unsorted
temp = array[i]; //save the element
int j = i-1;
while (temp.compareTo(array[j]) < 0 && j >= 0) { // while temp is less than array[j]
array[j+1] = array[j];
j--;
} //end of while
array[j+1] = temp; //as soon as temp is greater than array[j], set array[j] equal to temp
}
}
這回在while循環線的ArrayIndexOutOfBoundsException
,但是當我切換的條件while循環圍繞此:
while (j >= 0 && temp.compareTo(array[j]) < 0)
它的工作。我沒有想到在Java中,while循環中的條件順序與程序無關嗎?這對我來說很奇怪,因爲我從來沒有見過或聽說過在&&
的聲明中發出的命令,因爲我認爲兩條while循環行是等價的。我被困住了一會兒,並找不到答案。
有人可以解釋爲什麼這樣嗎?
如果第一個表達式評估爲「false」,那麼'&&'不會計算第二個表達式。閱讀[定義的第一行](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.23)。 – 4castle
條件從左到右進行評估。 java使用短路邏輯。對於AND操作,如果左邊的條件爲假,那麼它不會評估右邊的條件。 –
這*編譯*就好了。我願意成爲它不正確運行*。 – Makoto