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);
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);