Even though you clear the values in the list
, the Map
is still referencing the original list
, so any changes you make to that list will affect the original location as well.
Take a look at this example modified from your code:
Map<String, List<Object>> mp = new HashMap<>();
for (int k = 65; k <= 91; k++) {
List<Object> l = new ArrayList<>();
l.add((char)k);
mp.put(Integer.toString(k), l);
}
System.out.println(mp);
This will print a Map
pairing for each letter A
to Z
with the respective ASCII values for the letter.
{66=[B], 88=[X], 67=[C], 89=[Y], 68=[D]...etc...
However what happens if you change the code to clear
the list like you have in your code right before the print
and only declare a new List
a single time outside of the loop:
Map<String, List<Object>> mp = new HashMap<>();
List<Object> l = new ArrayList<>();
for (int k = 65; k <= 91; k++) {
l.add((char)k);
mp.put(Integer.toString(k), l);
}
l.clear();
System.out.println(mp);
This will now print this:
{66=[], 88=[], 67=[], 89=[], 68=[], 69=[], 90=[] ...etc...
With every List
value in the Map
blank because they were all referencing the same list that was cleared at the end.
Now it may seem obvious that they would all be cleared because inside of the loop we did not clear the List
each iteration and just added every value into the List
all together, so clearly the Map
is referencing the same List
!
However, using clear
has nothing to do with referencing the same list
or not, it just makes it seem like you did not just add all of the values into the same list, but you did.