You can't do it the way you're trying to... But you can perhaps do something like this:
List<Answer> answers = new ArrayList<Answer>();
for(int i=0; i < 4; i++){
Answer temp = new Answer();
// Do whatever initialization you need here
answers.add(temp);
}
Answer from Chris on Stack OverflowYou can't do it the way you're trying to... But you can perhaps do something like this:
List<Answer> answers = new ArrayList<Answer>();
for(int i=0; i < 4; i++){
Answer temp = new Answer();
// Do whatever initialization you need here
answers.add(temp);
}
That can't be done with a for-loop, unless you use the Reflection API. However, you can use Arrays.asList instead to accomplish the same:
List<Answer> answers = Arrays.asList(answer1, answer2, answer3);
java - How to add to ArrayList in a For loop - Stack Overflow
java - adding elements to an ArrayList using a loop and outputting them on console - Stack Overflow
How to fill out an ArrayList with for each loop? (Java) - Stack Overflow
Is there a way to add elements to an Array List all at once?
The problem is that your array list is empty (size = 0) before you start adding to it; So your loop is running on empty.
Enhanced for-loop will also not work because the list has no items in the first place.
When you add them manually, you successfully get items into the list because you were not depending on the size of the list.
Make use of the alternate implementation in Mert Ozdal's answer
test_list.size() is Zero in your loop. You need to specify the number of steps the for loops
The solution is simple
final int[] numbers = new int[] {2,4,6,8,10,12,14,16,18,20};
final List<Integer> list = new ArrayList<Integer>();
for (int number : numbers) {
list.add(number);
}
Something like this maybe?
IntStream.range(0, 10).map(y -> 2 + y * 2).forEach(arraylist::add);
For example I can do this with a basic integer array:
int[] test1 = new int[]{2, 1, 5, 1, 3, 2};But with an Array list I have to add them one at a time like this
List<Integer> test1 = new ArrayList<Integer>(); test1.add(2); test1.add(1); test1.add(3);
?