Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Add elements to arraylist with FOR loop where element name has increasing number

Tags:

java

for-loop

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?

like image 757
Rupal Avatar asked Nov 25 '11 12:11

Rupal


People also ask

How do you increment an element in an ArrayList?

You can't increment the value in place since Integer objects are immutable. You'll have to get the previous value at a specific position in the ArrayList , increment the value, and use it to replace the old value in that same position. Alternatively, use a mutable integer type, like AtomicInteger (or write your own).

Can we add elements while iterating in ArrayList?

You can't modify a Collection while iterating over it using an Iterator , except for Iterator. remove() . This will work except when the list starts iteration empty, in which case there will be no previous element. If that's a problem, you'll have to maintain a flag of some sort to indicate this edge case.

What happens when you add an element that exceeds the ArrayList capacity?

Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding elements, the capacity is automatically increased by reallocating the internal array before copying the old elements and adding the new elements.


2 Answers

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);
}
like image 187
Chris Avatar answered Oct 06 '22 09:10

Chris


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);
like image 31
João Silva Avatar answered Oct 06 '22 09:10

João Silva