deadpool
deadpool

Reputation: 456

HashMap Value replacing old value even if for a new Key in java

I have a simple observation with a Map with String keys of date format.

List<String> a =new ArrayList();
a.add("as");
a.add("df");
a.add("vf");
a.add("fg");
HashMap<String,List> map = new HashMap<>();
map.put("2017-08-07", a);
System.out.println(""+map);
a.clear();
a.add("er");
map.put("2017-08-08", a);
System.out.println(""+map);

And Result is

{2017-08-07=[as, df, vf, fg]}
{2017-08-08=[er], 2017-08-07=[er]}

when i am clearing list and assign new key to my map then my old value also replacing.

But i want result be like

{2017-08-07=[as, df, vf, fg]}
{2017-08-08=[er], 2017-08-07=[as, df, vf, fg]}

How to achieve this, Any help really appreciated . Thanks

Upvotes: 1

Views: 2928

Answers (3)

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37624

The call on map.put does not mean that it will create an entirely new value for the List. You put a reference to the current List a there and if you modify a it will also modify it inside the Map. To avoid that, create a new List.

Change this line

map.put("2017-08-07", a);

to

map.put("2017-08-07", new ArrayList<>(a));

Upvotes: 1

Max M
Max M

Reputation: 581

Put a new List to map, so a won't be linked.

map.put("2017-08-07", new List<String>(a));

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122026

Thats because you are modifying the same instance of list, hence the modifications will effect everywhere. Create a new list if you want to have separate results otherwise you lost all the data everywhere when you clear it.

map.put("2017-08-07", a);
System.out.println(""+map);
List<String> b = new ArrayList<>();
b.add("er");
map.put("2017-08-08", b);
System.out.println(""+map);

Upvotes: 0

Related Questions