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
storageUnit newUnit = new storageUnit();
for (int i = 0; i < list1.size(); i++) {
newUnit.category = list1.get(i);
list2.add(newUnit);
}
to
for (int i = 0; i < list1.size(); i++) {
storageUnit newUnit = new storageUnit();
newUnit.category = list1.get(i);
list2.add(newUnit);
}
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 newUnit object each time.
When you add newUnit to list2, you're adding the same instance of storageUnit 5 times. This means if you change one, you'll change the rest. You need to declare a new storage unit every time you add to list2.
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<storageUnit> list2 = new ArrayList<storageUnit>();
for (int i = 0; i < list1.size(); i++) {
storageUnit newUnit = new storageUnit();
newUnit.category = list1.get(i);
list2.add(newUnit);
}
static class storageUnit {
String category;
Hashtable<String, Integer> wordTable = new Hashtable<String, Integer>();
};
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