繁体   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