Main Class --
package test; import java.util.Map; public class Client { private static ArrayList<Class1> allInstances = new ArrayList<Class1>(); private static Map <String, String> var1 = new HashMap<String, String>(); public static void main(String[] args) { var1.put("key1","value1"); Class1 instance1 = new Class1(var1); allInstances.add(instance1); var1.put("key2","value2"); Class1 instance2 = new Class1(var1); allInstances.add(instance2); getInstances(); } public static void getInstances() { for(Class1 c: allInstances) { System.out.println(c.getClassDetails()); } } Class Class1 --
package test import java.util.Map; public class Class1 { private Map <String, String> classDetails; public Class1(Map <String, String> classDetails) { this.classDetails = classDetails; } public Map <String, String> getClassDetails(){ return this.classDetails; } } Output--
{key2=value2} {key2=value2} As we can see from the output above, both instances variable returns the same updated value. Should'nt instance1 return {key1=value1}
Also, if this is the expected behavior, what can be done to tackle this issue.
Class1instances use references to the sameHashMapthough. If you want them to be independent, they should have independent map objects.