[英]Getting "IndexOutOfBoundsException: Index 20 out of bounds for length 4" while using for-each loop with ArrayList of integers
I'm a newbie and I'm trying to learn, so don't blast me please.我是新手,我正在努力学习,所以请不要抨击我。
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;
}
}
So, this is a simple code that I was using for learning some stuff.所以,这是我用来学习一些东西的简单代码。 I tried to create a sum method with an ArrayList of integers as a parameter.
我尝试使用整数的 ArrayList 作为参数创建求和方法。 I tried to use a for-each loop to sum each value, but I got the error:
我尝试使用 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]
I don't understand why I get this error, if I use a simple for loop it works.我不明白为什么会出现此错误,如果我使用简单的 for 循环它可以工作。 Sorry if it's a stupid question but like I said, I'm trying to learn so please be kind with me, thanks.
抱歉,如果这是一个愚蠢的问题,但就像我说的那样,我正在努力学习,所以请对我好一点,谢谢。
The for-each
loop iterates the values, not the indexes. for-each
循环迭代值,而不是索引。
for (int i : values) {
sum += values.get(i);
}
should be应该
for (int i : values) {
sum += i;
}
If using Java 8+, you could map to an IntStream
and sum like如果使用 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.