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?
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).
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.
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.
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);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With