0

I am trying to populate an ArrayList using a loop. What am I doing wrong? When I print the ArrayList nothing gets printed. I think my problem is related to numbers.size().

ArrayList<Integer> numbers = new ArrayList<>(7);
for (int i = 1; i <= numbers.size(); i++) {
    numbers.add(i);
}
2

4 Answers 4

2

In line ArrayList<Integer> numbers = new ArrayList<>(7); 7 - isn't size. Size still equal 0, because you didn't add any elements. So numbers.size() is 0.

Argument in constructor is initialCapacity. This is a start length of internal array in ArrayList.

Sign up to request clarification or add additional context in comments.

5 Comments

Ah I see, how could I add values using a loop. Is that possible?
@Carl Just replace i <= numbers.size() to i <= 7
@VladimirParfenov Not a good idea to hardcode it
Just define a int variable int SIZE to your desired length and then do for int i = 0; i < SIZE; i++
I understand now guys, thanks for your help
1

Initially, the list is empty, meaning numbers.size() returns 0. Therefore the loop will never be entered because 1 <= 0 is false.

1 Comment

Ah I see, how could I add values using a loop. Is that possible?
1

The problem is with numbers.size(). This line ArrayList<Integer> numbers = new ArrayList<>(7); create an ArrayList with initial capacity enough equal or higher than 7 but the size of the created ArrayList is 0. So the program doesn't go instead your loop

1 Comment

I understand now, thanks for your help
1

You have two problems here:

ArrayList<Integer> numbers = new ArrayList<>(7);

You need to specify the type for both sides of the assignment

for (int i = 1; i <= numbers.size(); i++) {
    numbers.add(i);

Indexes for arrays and ArrayLists start at 0, so make i zero, and use a less-than instead of less-than-or-equal-to. Finally, this should work. Just edited this, seems like I was slightly wrong. Make numbers.size() a constant instead, and that should work

ArrayList<Integer> numbers = new ArrayList<Integer>(7);
 for (int i = 0; i < 7; i++) {
    numbers.add(i);
}

2 Comments

"You need to specify the type for both sides of the assignment" if you are talking about generic type then it since Java 7 we can use diamond operator <> instead of rewriting generic type again.
I understand now, thanks for your help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.