![](/img/trans.png)
[英]Arraylist java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3 Error
[英]How to fix ArrayList java.lang.IndexOutOfBoundsException: Index 20 out-of-bounds for length 2
我想將不成對的數字存儲在我的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)
當您嘗試從數組colors
刪除重復項時,您將獲得IndexOutOfBoundsException
。 這是因為ArrayList
的remove()
方法可以接受Object
或int
而您要傳入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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.