Monday, July 29, 2019

java - When a map variable is passed to constructor of different instances, all instances member variables are updated to latest value of map





Main Class --



package test;
import java.util.Map;

public class Client {
private static ArrayList allInstances = new ArrayList();
private static Map var1 = new HashMap();

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 classDetails;

public Class1(Map classDetails) {
this.classDetails = classDetails;
}


public Map 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.


Answer



As it is appeared from your code, you referenced same HashMap to instacne1 and instance2 objects and in getClassDetails method the tostring method of same hashmap will invoked so the outputs is the same , use this code snippet :



import java.util.*;


public class Main {
private static ArrayList allInstances = new ArrayList();

public static void main(String[] args)
{
Map var = new HashMap();
var.put("key1","value1");
Class1 instance1 = new Class1(var);
allInstances.add(instance1);


var = new HashMap();
var.put("key2","value2");
Class1 instance2 = new Class1(var);
allInstances.add(instance2);

getInstances();
}

public static void getInstances() {

for(Class1 c: allInstances)
System.out.println(c.getClassDetails());
}
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...