Java: LinkedHashMaps overlaps over themselves -
i want create copy of linked hash map , want remove values (from list) instead of first entry. here got:
linkedhashmap<string, list<value>> facetsincategoriescopy = new linkedhashmap<>(facetsincategories); if (!facets.equals("something")) { (list<value> value : facetsincategoriescopy.values()) { if (value.size() > 1) { int nbrofelements = value.size(); (int = nbrofelements-1; > 0; i--) { value.remove(i); } } } }
after operation turns out facetsincategories modified too. why? , how solve issue? appreciated.
i don't have 50 reputation add comment. see answer assigning hashmap hashmap
essentially, copy constructor used make new map has references mutable objects i.e. facetsincategories
, update when update facetsincategoriescopy
map.
the solution instead deep copy instead. have added test code below, used string
instead of value
//test https://stackoverflow.com/questions/27324315/ public static void teststacko_q_27324315() { map<string, list<string>> facetsincategories = new linkedhashmap<string, list<string>>(); string[] values = new string[]{"test1", "test2", "test3"}; list<string> valueslist = new arraylist<string>(arrays.aslist(values)); facetsincategories.put("test", valueslist); map temp = collections.unmodifiablemap(facetsincategories); linkedhashmap<string, list<string>> facetsincategoriescopy = (linkedhashmap<string, list<string>>)deepcopy(temp); string facets = "test_me"; if (!facets.equals("something")) { (list<string> value : facetsincategoriescopy.values()) { if (value.size() > 1) { int nbrofelements = value.size(); (int = nbrofelements-1; > 0; i--) { value.remove(i); } } } } system.out.println(facetsincategories); system.out.println(facetsincategoriescopy); } public static <k1, k2, v> map<k1, list<v>> deepcopy( map<k1, list<v>> original){ map<k1, list<v>> copy = new linkedhashmap<k1, list<v>>(); for(map.entry<k1, list<v>> entry : original.entryset()){ copy.put(entry.getkey(), new arraylist<v>(entry.getvalue())); } return copy; }
Comments
Post a Comment