Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList Help

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?

like image 386
TookTheRook Avatar asked Apr 28 '26 11:04

TookTheRook


2 Answers

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.

like image 89
Alan Geleynse Avatar answered May 01 '26 01:05

Alan Geleynse


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>();
};
like image 32
thattolleyguy Avatar answered May 01 '26 01:05

thattolleyguy