I have an arraylist where I want to add elements via a for loop.
Answer answer1;
Answer answer2;
Answer answer3;
ArrayList answers = new Array
why you need a for-loop for this? the solution is very obvious:
answers.add(answer1);
answers.add(answer2);
answers.add(answer3);
that's it. no for-loop needed.
Put the answers into an array and iterate over it:
List<Answer> answers = new ArrayList<Answer>(3);
for (Answer answer : new Answer[] {answer1, answer2, answer3}) {
list.add(answer);
}
EDIT
See João's answer for a much better solution. I'm still leaving my answer here as another option.
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);
There's always some reflection hacks that you can adapt. Here is some example, but using a collection would be the solution to your problem (the integers you stick on your variables name is a good hint telling us you should use a collection!).
public class TheClass {
private int theField= 42;
public static void main(String[] args) throws Exception {
TheClass c= new TheClass();
System.out.println(c.getClass().getDeclaredField("theField").get(c));
}
}
Thomas's solution is good enough for this matter.
If you want to use loop to access these three Answers, you first need to put there three into an array-like data structure ---- kind of like a principle. So loop is used for operating on an array-like data structure, not just simply to simplify typing task. And you cannot use FOR loop by simply just giving increasing-number-names to the elements.
Using Random function to generate number and iterating them on al
using for loop
ArrayList<Integer> al=new ArrayList<Integer>(5);
for (int i=0;i<=4;i++){
Random rand=new Random();
al.add(i,rand.nextInt(100));
System.out.println(al);
}
System.out.println(al.size());