簡體   English   中英

在使用帶有整數 ArrayList 的 for-each 循環時獲取“IndexOutOfBoundsException:索引 20 超出長度 4 的范圍”

[英]Getting "IndexOutOfBoundsException: Index 20 out of bounds for length 4" while using for-each loop with ArrayList of integers

我是新手,我正在努力學習,所以請不要抨擊我。

import java.util.ArrayList;

public class Dummy {

  public static void main(String[] args) {

    ArrayList<Integer> values = new ArrayList<Integer>();
    values.add(20);
    values.add(10);
    values.add(50);
    values.add(20);

    System.out.println(add(values));

  }

  static int add(int a, int b) {
    return a + b;
  }

  static int add(int a, int b, int c) {
    return a + b + c;
  }

  static int add(ArrayList<Integer> values) {
    int sum = 0;

    for (int i : values) {
      sum += values.get(i);
    }
    return sum;
  }

}

所以,這是我用來學習一些東西的簡單代碼。 我嘗試使用整數的 ArrayList 作為參數創建求和方法。 我嘗試使用 for-each 循環對每個值求和,但出現錯誤:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 20 out of bounds for length 4
    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:266)
    at java.base/java.util.Objects.checkIndex(Objects.java:359)
    at java.base/java.util.ArrayList.get(ArrayList.java:427)
    at Dummy.add(Dummy.java:29)
    at Dummy.main(Dummy.java:13)
[Finished in 1.245s]

我不明白為什么會出現此錯誤,如果我使用簡單的 for 循環它可以工作。 抱歉,如果這是一個愚蠢的問題,但就像我說的那樣,我正在努力學習,所以請對我好一點,謝謝。

for-each循環迭代值,而不是索引。

for (int i : values) {
  sum += values.get(i);
}

應該

for (int i : values) {
  sum += i;
}

如果使用 Java 8+,則可以將 map 用於IntStream並求和

static int add(List<Integer> values) {
    return values.stream().mapToInt(Integer::intValue).sum();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM