Reputation: 384
I am adding/editing objects that are values in a hashmap-- with different keys.
However, editing one object in the hashmap seems to edit them all(?)
What am I doing wrong here?
First, my (poorly named) hashmap class:
import java.util.HashMap;
public class hashmap {
static HashMap<Integer, exObj> hm;
hashmap(){
hm = new HashMap<Integer, exObj>();
}
public void createVal(){
for (int i = 0; i<10; i++){
hm.put(i, new exObj(i));
}
hm.get(2).setValue();
}
public void printVal(){
for (int i = 0; i<10; i++){
System.out.println(hm.get(i).getValue());
}
}
public static void main(String args[]){
hashmap hmap = new hashmap();
hmap.createVal();
hmap.printVal();
}
}
Second, my simple exObj Class:
public class exObj {
private static int value;
exObj(int i){
value = i;
}
public void setValue(){
value = value + 1;
}
public int getValue(){
return value;
}
}
returns output:
10
10
10
10
10
10
10
10
10
10
Upvotes: 0
Views: 1747
Reputation: 3133
As @Jeff Foster and @Jesper said, it's all about using a static variable. Just to add some more info on your example, by running the code
for (int i = 0; i<10; i++){
hm.put(i, new exObj(i));
}
the last exObj that gets initialized get the value '9', which is shared for all the instances. Then by calling
hm.get(2).setValue();
the value is set as '10'
You can simply declare the 'value' as
private int value;
so every instance of exObj will have it's own value. Also remember to have your Class names starting with a capital letter, as a good practice
Upvotes: 0
Reputation: 206996
This is because value
in your class exObj
is static
:
public class exObj {
private static int value;
Because it is static
, there is only one copy of the variable, which is shared by all exObj
objects.
See Understanding Instance and Class Members.
Upvotes: 2
Reputation: 44746
You have static data which is shared amongst all instances of a class.
Try changing your class to have instance data (i.e. simply remove the static on private int value
).
Upvotes: 5