0

I wrote the following code to associate a key with a list of strings.When I display it,the values of the list for key '2' is being replaced by the values for key '4'.Shouldn't '2' point to the values it was mapped to?

 Map<Integer,List<String>>hm=new TreeMap<Integer,List<String>>();
 List<String>l=new ArrayList<String>();
 l.add("tree");
 l.add("tyre"); 
 hm.put(2, l);
 l.clear();
 l.add("treaaae");
 l.add("tyret");
 l.add("treeeqqq");
 l.add("tyreqww");
 hm.put(4, l);
  • 2
    `hm.put(2, l)` does not copy your list into the map. So when you call `l.clear()` later, you are clearing the same list as you have in your map. You could do this to make it work: `hm.put(2, new ArrayList<>(l));` – marstran Aug 17 '18 at 08:13

1 Answers1

0

The problem is that you keep using the list l, so actually both items 2 and 4 point to the same list.

This will work:

Map<Integer,List<String>>hm=new TreeMap<Integer,List<String>>();
List<String>l=new ArrayList<String>();
l.add("tree");
l.add("tyre"); 
hm.put(2, l);
List<String>m=new ArrayList<String>();
m.add("treaaae");
m.add("tyret");
m.add("treeeqqq");
m.add("tyreqww");
hm.put(4, m);
nsndvd
  • 800
  • 8
  • 21
  • So we are creating new list object Everytime we put a key.... – user10040367 Aug 17 '18 at 08:18
  • @user10040367 that's how it works :) if you want a hashMap of lists, that contains 2 lists, you have to create 2 lists. Maybe your purpose is different and there is a different way to handle it? – nsndvd Aug 17 '18 at 08:20