The value in LinkedHashMap cleared when I try to clear the object value (Java)

Tags: , ,



i got a problem when using LinkedHashMap. I try to store some value in it and then updated it.

I’m using String for the key and List for the value. I put 2 value on the List and put them to LinkedHashMap. the next step, i want to update one of the value in LinkedHashMap. I clear the List and put new value to it and the update the value in LinkedHashMap.

but something strange happen, when i clear the value in List, the value in LinkedHashMap is cleared too.

anyone have any suggestion regarding this issue?

Thank you.

here is the source code:

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class TestLinkedHash {

    private static LinkedHashMap<String, List<Object>> linkObj = new LinkedHashMap<String, List<Object>>();
    private static List<Object> test =  new ArrayList<Object>();
    
    public static void main(String[] args) {
        long timestamp = System.currentTimeMillis();
        double value = 900.0;
        
        String key = "TPS";
        String key1 = "TEST"; 
        String key2 = "TOST";
        
        test.add(timestamp);
        test.add(value);
        
        linkObj.put(key, test);
        linkObj.put(key1, test);
        linkObj.put(key2, test);
        System.out.println(linkObj);    
        
        test.clear();
        System.out.println(linkObj);
        
        test.add(System.currentTimeMillis());
        test.add(200.0);
        linkObj.put(key, test);
        System.out.println(linkObj);
    }
}

Answer

Your collection holds references to test. Since that, when test is cleared, your collection will have references to empty list.

If you will insert the shallow copy of an object to the collection, change of original object will not affect its copy. However, reference is pointing to a certain segment of memory, whereas when it mutates, all the mutations are visible and accessible by the reference.

UPD: The change of an object is shared, since the object you modify is the same object that you have inserted in your collection.



Source: stackoverflow