EDWIN CHEN
EDWIN CHEN

Reputation: 85

How to fill in only the even indexes of an ArrayList?

So I was trying to produce an arraylist where the even indexes were all filled. Something like this [1, -, 1, -, 1, -........]. But it's giving me an index out of bounds error. Why is that?

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        ArrayList<Integer> a = new ArrayList<>(10);

        for (int i=0; i<11; i+=2) {
            a.add(i, new Integer(1234));
        }
    }
}

Upvotes: 1

Views: 791

Answers (3)

Andrew Vershinin
Andrew Vershinin

Reputation: 1968

First, you loop constraint is off, for an array (and ArrayList) of size 10, indices are 0 through 9, means you need to check for i < 10.
Second, the parameter of ArrayList constructor (10 in this case) is the capacity, but not size - it's still empty, no actual elements in there. So you need to add zeroes (or nulls) in the loop too:

for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        a.add(1234);
    } else {
        a.add(0); // or a.add(null)
    }
}

Upvotes: 0

mymoto
mymoto

Reputation: 341

Remember indices always start with 0. You've created an arraylist with size 10, which means you should iterate through index 9, not 10.

Your for loop should be:

for (int i = 0; i < 10; i += 2)

Upvotes: 1

michael_fortunato
michael_fortunato

Reputation: 168

Arrays use zero based indexing meaning you can reference a[0] through a[9]. so your constraint in the for loop Should be i < 10. I’ll edit this answer and give more detail when I get home.

Upvotes: 0

Related Questions