如何修复 ArrayList java.lang.IndexOutOfBounds

我想在我的 arrayList“颜色”中存储没有配对的数字,但我的 arrayList 收到此运行时错误。main 获取 n(数组大小)的输入和 arItems 的输入,然后将 arItems 中的元素转换为整数,将它们放入 int 数组 ar 中,然后当它调用 sockMerchant 时,它传递 int n 和 int 数组 ar


static int sockMerchant(int n, int[] ar) {

    ArrayList<Integer> colors = new ArrayList<Integer>(n);

    int pairs = 0;


    for (int i = 0; i < n; i++) {

       if (!colors.contains(ar[i])) {

            colors.add(ar[i]);

        } else {

            pairs++;

            colors.remove(ar[i]);

        }

    }


    System.out.println(pairs);

    return pairs;

}

private static final Scanner scanner = new Scanner(System.in);


public static void main(String[] args) throws IOException {


    // n is the size of the array

    // sample n input: 9

    int n = scanner.nextInt();

    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");


    int[] ar = new int[n];


    //sample arItems input: 10 20 20 10 10 30 50 10 20

    String[] arItems = scanner.nextLine().split(" ");

    scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");


    for (int i = 0; i < n; i++) {

        int arItem = Integer.parseInt(arItems[i]);

        ar[i] = arItem;

    }


    int result = sockMerchant(n, ar);



    scanner.close();

}

我得到的错误是:


Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 20 out-of-bounds for length 2

    at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)

    at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)

    at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)

    at java.base/java.util.Objects.checkIndex(Objects.java:372)

    at java.base/java.util.ArrayList.remove(ArrayList.java:517)

    at Solution.sockMerchant(Solution.java:21)

    at Solution.main(Solution.java:48)


呼如林
浏览 56回答 1
1回答

繁花不似锦

IndexOutOfBoundsException当您尝试从数组中删除重复项时,您会收到colors。这是因为remove()的方法ArrayList可以接受 anObject或 anint并且您正在传递一个int。这意味着您实际上正在尝试删除特定索引,在您的示例中是索引 20,但该索引在您的数组中不存在。您可以修改代码以根据索引正确删除值。static int sockMerchant(int n, int[] ar) {&nbsp; &nbsp; ArrayList<Integer> colors = new ArrayList<Integer>(10);&nbsp; &nbsp; int pairs = 0;&nbsp; &nbsp; for (int i = 0; i < n; i++) {&nbsp; &nbsp; &nbsp; &nbsp;if (!colors.contains(ar[i])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; colors.add(ar[i]);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pairs++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; colors.remove(color.indexOf(ar[i]));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(pairs);&nbsp; &nbsp; return pairs;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java