当我使用增强的 for 循环时出现 ArrayIndexOutOfBound 错误

ArrayIndexOutOfBound error when i used enhanced for loop

我们可以使用增强的 for 循环而不出现 ArrayIndexOutOfBound 错误吗? 因为在使用正常的 for 循环后它可以正常工作。

    public static void main(String[] args) {
        int a[] = {1,2,3,4};
        int b[] = {1,2,3,4};
 boolean status = true;
        if (a.length == b.length){
            for (int i:a){
                if (a[i] != b[i]){
                    status =false;
                }
            }
        }
        else {
            status = false;
        }

        if (status == true){
            System.out.println("arrays are equal...");
        }
        else {
            System.out.println("arrays not equal...");
        }
    }
}

那是因为您正在访问数组 a 的元素。

循环

for (int i : a) {
  System.out.println(i);
}

将打印出值:1、2、3、4。

您可能希望得到 0、1、2、3,但这不是增强循环的工作方式。

改进

您可以使用便捷方法 Arrays.equals():

而不是手动比较两个数组
public static void main(String[] args) {
    int a[] = {1,2,3,4};
    int b[] = {1,2,3,4};
    boolean status = java.util.Arrays.equals(a, b);

    if (status){
        System.out.println("arrays are equal...");
    } else {
        System.out.println("arrays not equal...");
    }
}

for (int i:a) // 你错了,我等于 1,2,3,4 数组索引必须从 0

开始
 public static void main(String[] args) {
        int a[] = {1,2,3,4};
        int b[] = {1,2,3,4};
 boolean status = true;
        if (a.length == b.length){
            for (int i=0; i<a.length; i++){  // look at here 
                if (a[i] != b[i]){
                    status =false;
                }
            }
        }
        else {
            status = false;
        }

        if (status == true){
            System.out.println("arrays are equal...");
        }
        else {
            System.out.println("arrays not equal...");
        }
    }
}