简体   繁体   中英

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. I tried to use a for-each loop to sum each value, but I got the error:

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. 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 (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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM