In my code I have an ArrayList contentChecklist which stores HashMap objects in it. After adding all the HashMap objects in the List, and if I get the last HashMap object from the list and store it in new HashMap object (CheckListMaptemp) and use CheckListMaptemp.put("place", "somePlace");
. It is modifying the original HashMap oject present in the List.
public static void main(String[] args) {
List<HashMap> contentChecklist = new ArrayList<>();
Map<String,String> checklIstMap1= new HashMap<>();
checklIstMap1.put("name", "name1");
checklIstMap1.put("uuid", "001");
contentChecklist.add(checklIstMap1);
Map<String,String> checklIstMap2= new HashMap<>();
checklIstMap2.put("name", "name2");
checklIstMap2.put("uuid", "002");
contentChecklist.add(checklIstMap2);
Map<String,String> CheckListMaptemp= (Map<String, String>) contentChecklist.get(contentChecklist.size()-1);
CheckListMaptemp.put("place", "somePlace");
for (Iterator iterator = contentChecklist.iterator(); iterator.hasNext();) {
Map object = (Map) iterator.next();
String val = (String) object.get("place");
System.out.println(val);
}
}
The output is :
nullsomePlace
I know this is the correct behaviour , but I am eager to know how contentChecklist contents gets modified when we invoke CheckListMaptemp.put("place", "somePlace");
on CheckListMaptemp , even though both are different objects .