6

I have an arraylist where I want to add elements via a for loop.

Answer answer1;
Answer answer2;
Answer answer3;

ArrayList<Answer> answers = new ArrayList(3);

for (int i=0; i<3; i++)
{
    answers.add( /* HOWTO: Add each of the answers? */ );
}

How would this go if I have, let's say, 50 Answer elements?

2
  • i think the importent question is: what's your input? do you want to add fields? or an array? or another list? Commented Nov 25, 2011 at 12:16
  • Thaks for input every one. I think I need to redefine the way I'm trying to do this... Best hint for me was what Chris wrote.. I'm going with that. Commented Nov 25, 2011 at 12:27

9 Answers 9

18

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);
}
Sign up to request clarification or add additional context in comments.

Comments

8

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

2 Comments

This doesn't work, I'm getting incompatible types: no instance(s) found of type variable(s) T exist so that java.util.List<T> conforms to java.util.ArrayList.
set your variable type to List instead of ArrayList. It's a good habit to use the lowest possible interface.
4

I assume Answer as an Integer data type, so in this case you can easily use Scanner class for adding the multiple elements (say, 50).

private static final Scanner obj = new Scanner(System.in);
private static ArrayList<Integer> arrayList = new ArrayList<Integer>(50);

public static void main(String...S) {

  for (int i=0; i<50; i++) {
    /* Using Scanner class object to take input. */
    arrayList.add(obj.nextInt());
  }

  /* You can also check the elements of your ArrayList. */
  for (int i=0; i<50; i++) {
    /* Using get function for fetching the value present at index 'i'. */
    System.out.print(arrayList.get(i) + " ");
  }

}

This is a simple and easy method for adding multiple values in an ArrayList using a for loop.

As in the above code, I presume the Answer as Integer. It could be String, Double, Long, etc. So, in that case, you can use next(), nextDouble(), and nextLong(), respectively.

Comments

3

If you simply need a list, you could use:

List<Answer> answers = Arrays.asList(answer1, answer2, answer3);

If you specifically require an ArrayList, you could use:

ArrayList<Answer> answers = new ArrayList(Arrays.asList(answer1, answer2, answer3));

Comments

2

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

Comments

1

You do not 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.

3 Comments

I guess there are probably more than 3, and the the total number can change
Yes, it's easy enough for 3 elements, but what if I have 100?
but: are the answers fields? - in his example they are. what's the input?
1

Another option is to 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);
}

But see João's answer for a much better solution.

Comments

1

Thomas's solution is good enough for this matter.

If you want to use a 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 a loop is used for operating on an array-like data structure, not just simply to simplify the typing task. And you cannot use a for loop by simply just giving increasing-number-names to the elements.

1 Comment

Re "And you cannot use a for loop by simply just giving increasing-number-names to the elements.": Why not? Couldn't reflection be used?
1

Using the Random function to generate numbers and iterating them on al using a 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());

2 Comments

Hi Shubham, read the question again - he is looking for increasing number, not random
You can just remove random function and simply use increasing number instead off providing random numbers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.