如何修复ArrayList java.lang.IndexOutOfBoundsException:索引20超出长度2的边界

问题描述 投票:0回答:1

我想将不成对的数字存储在我的arrayList“ colors”中,但我的arrayList出现此运行时错误。主体获取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)

我想将不成对的数字存储在我的arrayList“ colors”中,但我的arrayList出现此运行时错误。主体获取n(数组大小)的输入和arItems的输入,然后将其转换为...

java runtime-error indexoutofboundsexception
1个回答
0
投票

当您尝试从阵列IndexOutOfBoundsException中删除重复项时,您会得到colors。这是因为remove()ArrayList方法可以接受Objectint,而您正在传递int。这意味着您实际上是在尝试删除特定的索引,在您的示例中为索引20,但是该索引在您的数组中不存在。]

您可以这样修改代码,以根据索引正确删除值。

static int sockMerchant(int n, int[] ar) {
    ArrayList<Integer> colors = new ArrayList<Integer>(10);
    int pairs = 0;

    for (int i = 0; i < n; i++) {
       if (!colors.contains(ar[i])) {
            colors.add(ar[i]);
        } else {
            pairs++;
            colors.remove(color.indexOf(ar[i]));
        }
    }

    System.out.println(pairs);
    return pairs;
}
© www.soinside.com 2019 - 2024. All rights reserved.