Danrex
Danrex

Reputation: 1655

How to change values in an array using for loop

Just two questions in regards to this code.

  1. How do I iterate through the array and actually change the values in the array.
  2. Why does the foreach keep giving me an out of bounds exception. It works fine for the usual for loop (int i = 0; i < anArray.length; i++), but I havn't used this foreach before?
package experimental;

import java.sql.Array;

public class foreachExp {

    public int[] anArray = {1, 2, 3, 4, 5,};

    public void foreachArray() {
        for (int i : anArray) {
            anArray[i] = i + 1;
        }
    }
}

Upvotes: 0

Views: 11744

Answers (3)

Rogue
Rogue

Reputation: 11483

for-each does not work based on array index but implements an iterative solution, the int i variable will be representative of a single element of data from your supplied array. So in the loop, you effectively call:

anArray[1] = 1 + 1;
anArray[2] = 2 + 1;
anArray[3] = 3 + 1;
anArray[4] = 4 + 1;
anArray[5] = 5 + 1;

As you can see, anArray[5] would be out of bounds, as the length of the array is only 5 long (0-4)

If you want to change the values, you do not use a for-each loop (could hackily do it using a Box of some sort, but with an array it would be silly to).

So with an array, this would be the advisable solution:

for (int i = 0; i < anArray.length; i++) {
    anArray[i]++;
}

As you have already mentioned

Upvotes: 6

Makoto
Makoto

Reputation: 106508

The fundamental difference between a for loop and an enhanced-for loop is that the enhanced-for loop actually binds the values of the array to the variable itself.

So, your enhanced-for is pulling this on each iteration:

  • i = 1
  • i = 2
  • i = 3
  • i = 4
  • i = 5 // this is the size of your array

Enhanced for loops aren't meant for changing values. You would use a normal for loop for that.

Upvotes: 2

akxlr
akxlr

Reputation: 1182

When you write

for (int i : anArray) {

i refers to the value itself, not the index. So asking for array[5] gives you an out of bounds exception (valid indices are 0 to 4).

You can instead use a normal for loop:

for (int i=0; i<anArray.length; ++i) {
    anArray[i]++;
}

Upvotes: 3

Related Questions