简体   繁体   中英

List values in a map

I wish to add list to map, but unable to get the desired output as a map. Any way to get the below desired output?

    List l = new ArrayList();

    Map<String, List<Object>> mp = new HashMap();

    l.add("A");

    mp.put("1", l);

    l.clear();
    l.add("B");

    mp.put("2", l);

    System.out.println(mp);

Expected :{1=[A], 2=[B]}

Actual :{1=[B], 2=[B]}

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.

    List l = new ArrayList();

    Map<String, List<Object>> mp = new HashMap();

    l.add("A");
    mp.put("1", l);

    l = new ArrayList();        
    l.add("B");
    mp.put("2", l);

    System.out.println(mp);

List was pass-by-reference so you need to create two different List

List l1 = new ArrayList();
l1.add("A");

List l2 = new ArrayList();
l2.add("B");

Map<String, List<Object>> mp = new HashMap();
mp.put("1", l1);
mp.put("2", l2);

System.out.println(mp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM