数组异常ArrayIndexOutOfBoundsException

时间:2015-09-24 00:20:18

标签: java arrays indexoutofboundsexception

我想问一些事情因为我不明白。 我想在数组中找到min元素,当我使用这段代码时它很好:

public static int najmanji(int[] niz) {
    int min = niz[0];
    for (int el = 0; el<niz.length; el++) {
        if (niz[el] < min) {
            niz[el] = min;
            return min;
        }
    }

    return min;

}

但是当我使用foreach循环时,我有异常ArrayIndexOutOfBoundsException

public static int najmanji(int[] niz) {
    int min = niz[0];
    for (int el : niz){
        if (niz[el] < min) {
            niz[el] = min;
            return min;
        }
    }

    return min;
 }

为什么我有这个错误?因为foreachfor循环相同?

1 个答案:

答案 0 :(得分:2)

el不代表索引;这是实际值。

for(int i = 0; i < myArray.length; i++){
    int curVal = myArray[i];
    //your code...
}

相同
for (int curVal : myArray){
    //your code...
}