1

How can I update the only str2 by not really updating str1 and str? Why is the change in str2 is updating str1 and str? Is it because of the object reference?

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class test {

    List<HashMap<String, String>> str;

    public static void main(String[] args) {
        Map<String, String> hmap = new HashMap<String, String>();
        hmap.put("1", "s1");
        hmap.put("2", "s2");
        test testobj = new test();
        testobj.str = new ArrayList<HashMap<String, String>>();
        testobj.str.add((HashMap<String, String>) hmap);
        testing(testobj.str);
    }

    static void testing(List<HashMap<String, String>> str) {

        List<HashMap<String, String>> str2 = new ArrayList<HashMap<String, String>>();
        List<HashMap<String, String>> str1 = str;
        str2.add(str1.get(0));
        str2.get(0).put("1", "new");

        System.out.println(str);
        System.out.println(str1);
        System.out.println(str2);

    }
}
NightOwl888
  • 55,572
  • 24
  • 139
  • 212

1 Answers1

0

You have to create a copy of the original List like this:

List<HashMap<String, String>> str1 = new ArrayList<>(str);

which creates a new ArrayList containing all the elements from the original List. This way you'll have two separate list containing its own elements.

whbogado
  • 929
  • 5
  • 15
  • OP isn't modifying the original list. – shmosel Apr 18 '18 at 02:00
  • not working :( its still updating all lists – Anony Michael Apr 18 '18 at 02:06
  • If you mean updating the HashMap inside the List, this is expected because you are adding the first HashMap inside str1 to str2: str2.add(str1.get(0)); After that you extract this same HashMap from str2 and put an element in it: str2.get(0).put("1", "new");. You are updating exactly the same HashMap. BTW, your code is very confusing. The str1 variable has no practical effect since it references the same List as str. – whbogado Apr 18 '18 at 02:17
  • So, how should I optimise it so I can have reference of str in str2 maybe and still have it not updated by str2? – Anony Michael Apr 18 '18 at 02:23