So let’s say I have an ArrayList of Strings, called list1, containing the strings, “A”, “B”, “C”, “D”, “E”. Then I have another ArrayList of type storageUnit, which is a class I wrote, called list2. Please see code below for a better explanation:
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<storageUnit> list2 = new ArrayList<storageUnit>();
storageUnit newUnit = new storageUnit();
for (int i = 0; i < list1.size(); i++) {
newUnit.category = list1.get(i);
list2.add(newUnit);
}
static class storageUnit {
String category;
Hashtable<String, Integer> wordTable = new Hashtable<String, Integer>();
};
Now if I try to print all the categories of all storageUnits in list2, I get [E, E, E, E, E] instead of [A, B, C, D, E]. Could anyone explain why this is happening?
Change
to
What your code was doing was creating a single object (
newUnit) and adding that to the list multiple times. Each time, you would overwrite it’s category, so when you printed the list you got the same value multiple times.Instead, you need to create a new
newUnitobject each time.