2
public static void main(String[] args) {
    List<Integer> values = new ArrayList<>(30);
    for (int i = 0; i < values.size(); i++){
        values.add(i, 0);
    }
    int j = 0;
    int ghh = values.get(j);
}

Above is a simple code snippet that gives an OutOfBoundException at the last line. Why is this exception being thrown? Do I actually need to use the for-loop for initiating 0 value of all the elements of the list?

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
Borislava
  • 49
  • 9

3 Answers3

4

Your for loop does nothing, since values.size() is 0. That's the reason why values.get(j) throws an exception (the list remains empty).

Change the loop to

for (int i = 0; i < 30; i++){
    values.add(i, 0);
}

When you create an ArrayList instance with this constructor - new ArrayList<>(30) - you are specifying the initial capacity, not the initial size. The initial size is 0.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
Eran
  • 387,369
  • 54
  • 702
  • 768
2

Your problem is that you assume new ArrayList<>(30) creates a list with 30 slots already "allocated" (so that .size() would return 30).

But that is not what actually happens. This constructor only specifies the initial capacity of the list. Meaning, you can now add 30 elements, and the underlying list will not need to dynamically grow. But you still have to add at least one element, before you can do a get(0).

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

The Array list constructor 'ArrayList(int initialCapacity)' creates an empty list with a initial capacity received.

List<Integer> values = new ArrayList<>(30);

values is an empty list at this point. You set an initial capacity but this doesn't create any element in the list.

for (int i = 0 ;i<values.size() ; i++){

values.size() is 0, so the line inside the loop is not being executed.

int ghh = values.get(j);

values is still an empty list, so values.get(0) throws an IndexOutOfBoundException

Do I actually need to use the for-loop for initiating 0 value of all the elements of the list?

You need to manually add the elements to the list using the for loop.

As an alternative, in Java8, you could use an Stream to generate the list:

List<Integer> list = Stream.generate(()-> 0).limit(30).collect(Collectors.toList());
David SN
  • 3,389
  • 1
  • 17
  • 21