Some quick tips:
- Consider following naming convention. Variable names starts with lowercase.
- Effective Java 2nd Edition, Item 65: Don't ignore exceptions
- Effective Java 2nd Edition, Item 52: Refer to objects by their interfaces
Having said that, you can add
to an ArrayList
the same way you add
to ANY List
: you can add(E)
a single element or addAll
an entire Collection<? extends E>
to the end of the list. There are also overloads that takes an index if you want to add element(s) to a more specific location.
On aliasing
Always remember that objects are reference types, and references can be aliased. Unless you understand what this means, some behaviors may surprise you.
This snippet shows an example of:
- Creating a
List
of 3 AtomicReference
instances that all refers to the same AtomicInteger
.
- When the
AtomicInteger
is incremented, all AtomicReference
sees this effect
- One
AtomicReference
is then set to refer to a second AtomicInteger
(There is nothing specific about concurrency in this example)
import java.util.concurrent.atomic.*;
//...
List<AtomicReference<AtomicInteger>> refs =
new ArrayList<AtomicReference<AtomicInteger>>();
AtomicInteger counter = new AtomicInteger();
for (int i = 0; i < 3; i++) {
refs.add(new AtomicReference<AtomicInteger>(counter));
}
// we now have 3 AtomicReference,
// but only 1 AtomicInteger
System.out.println(refs); // [0, 0, 0]
counter.incrementAndGet();
System.out.println(refs); // [1, 1, 1]
refs.get(1).set(new AtomicInteger(9));
System.out.println(refs); // [1, 9, 1]
// we still have only 3 AtomicReference,
// but we've also created a second AtomicInteger
counter.incrementAndGet();
System.out.println(refs); // [2, 9, 2]
Note that even though a new AtomicReference
was used for List.add
every time (meaning 3 different AtomicReference
objects are created total), they were still referring to the same AtomicInteger
. This sorts of aliasing may be the source of your problem.