Reputation: 53
I'm trying to use the following code to create HashMap
of custom Objects.
public static void test() {
programStats ps = new programStats();
programStats ps1 = new programStats();
List<programStats> psList = new LinkedList<programStats>();
ps.progName = "test1";
ps1.progName= "Test11";
psList.clear();
psList.add(ps);
Map<String,List<programStats>> d = new HashMap<String, List<programStats>>();
d.put("Test1", psList);
psList.add(ps1);
for (programStats p : d.get("Test1")) {
System.out.println(p.progName);
}
class programStats {
public static String progName, module;
public static int min, max, mean, mid, count;
public static List<Integer> data = new ArrayList<Integer>();;
}
I have noticed that when I'm setting the value to ps1
, the value of ps
is changing too.
What am I doing wrong?
Upvotes: 1
Views: 113
Reputation: 311143
All the members of your programStats
class are static
, meaning they belong to the class, not a specific instance.
So, regardless of which instance you use to modify them, those values would be visible via any instance. You should change them to instance members:
class programStats {
// Note: The member are no longer static:
public String progName, module;
public int min, max, mean, mid, count;
public List<Integer> data = new ArrayList<Integer>();
}
Upvotes: 2