【问题标题】:How to fix ArrayList java.lang.IndexOutOfBoundsException: Index 20 out-of-bounds for length 2如何修复 ArrayList java.lang.IndexOutOfBoundsException:长度为 2 的索引 20 越界
【发布时间】:2020-02-03 18:07:29
【问题描述】:

我想在我的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)

【问题讨论】:

  • 嘿,没有对是什么意思。在代码中添加函数调用@Janet
  • 是的,对不起,我将编辑代码
  • @NaveenJain 我编辑了代码并将函数调用包含在我的主要方法中:),我的数组中的示例输入是 10 20 20 10 10 30 50 10 20 我必须找到那里有多少对在数组中(10 有 2 对,20 有 1 对,30 和 50 没有一对,所以对的数量应该是“3”,这应该是程序的输出)。

标签: java runtime-error indexoutofboundsexception


【解决方案1】:

当您尝试从数组colors 中删除重复项时,您会得到一个IndexOutOfBoundsException。这是因为ArrayListremove() 方法可以接收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;
}

【讨论】:

  • 哦我忘了 remove 接受索引参数!!! T^T 感谢您指出这一点
猜你喜欢
  • 2017-06-30
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 2021-04-09
  • 1970-01-01
相关资源
最近更新 更多