benz
benz

Reputation: 725

Keep the value of the main map after clearing map

I have mainHolder map which contains another map holder as value I am facing problem when clearing the holder map that I am loosing the vlue of the apple key in the mainHolder map.

How can I Keep the value of the mainHolder map after Clearing the holder map?

Code

import java.util.HashMap;
import java.util.LinkedHashMap;


public class Generator {

    public static void main(String[] args) {

        LinkedHashMap<String, Object> holder = new LinkedHashMap<String, Object>();
        final HashMap<String, LinkedHashMap<String, Object>> mainHolder = new LinkedHashMap<String, LinkedHashMap<String, Object>>();

        holder.put("firstName", "Alex");
        holder.put("lastName", "Cruz");
        mainHolder.put("apple", holder);
        holder.clear(); //After Clearing the map I am loosing the value in the mainHolder for 'apple'
        holder.put("quantity", 13);
        mainHolder.put("apple", holder);
        System.out.println("Test");

    }
}

mainHolder should contain at the end the following:

[apple:[firstName: Fadi, lastName: Cruz, quantity:13]]

Upvotes: 1

Views: 87

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 19632

The reason this is happening is because you are using the same key.

If the map previously contains a mapping for the key, the old value is replaced.

Update

<>.add(map) will put a reference to map in the list, so it's not a copy. When you then do map.clear() afterwards, it erases the content of the map in the list too, because it is the very same object. Do <>.add(map.clone()) instead or (preferably) do map = new HashMap<>();

solution

LinkedHashMap<String, Object> holder = new LinkedHashMap<String, Object>();
final HashMap<String, LinkedHashMap<String, Object>> mainHolder = new LinkedHashMap<String, LinkedHashMap<String, Object>>();

holder.put("firstName", "Alex");
holder.put("lastName", "Cruz");
mainHolder.put("apple", holder);

holder = new LinkedHashMap<>();

LinkedHashMap<String, Object> temp = mainHolder.get("apple");
temp.put("quantity",13);
mainHolder.put("apple",temp);

System.out.println(mainHolder);

Upvotes: 1

Related Questions