I am trying to reinitialize my already existing list and use a list.clear() method to clean up a list before I push in new values into it and set the map based on the values in the list. My output for the below code is: -----1A-------- [first value, second value] -----1B-------- [third value, fourth value] PS: Both times I try to check if the map still holds the correct values which is where the code is breaking.
This same code works perfrctly fine if I replace the line initList.clear(); by initList = new ArrayList(3);
CORRECT OUTPUT: -----1A-------- [first value, second value] -----1B-------- [first value, second value]
You have a Map. In that Map are several keys. Associated with each key is a List of Strings. Have I got that right?
When you put a List (or any other object) into a Map (or any other Java container), that list is included by reference. That means that Map does not copy the List or its contents -- it just holds on to the original. So you're actually associating a single List object with two different keys. When you call initList.clear(), you're erasing the contents of that single List, and then you add new contents; now both keys are still associated with that one List, but now it hold different Strings.
The unavoidable truth is that you need to create a new List to hold the Strings associated with each key. Not sure why you think this is a bad thing; though. Maybe you've used STL containers in C++, which work by copying things; Java collections don't work that way.
You might want to have a look at this if this is at all unclear.
Finally, note that Java Strings are immutable; their contents cannot be changed. Therefore, it's never necessary to make a copy of them, as you're doing with 'new String("first value")'. That constructor is needed only in the most obscure of circumstances; don't use it, but rather just use the String literals as-is.