简体   繁体   中英

Java: Object as Value in HashMap being overwritten?

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

You have static data which is shared amongst all instances of a class.

Try changing your class to have instance data (ie simply remove the static on private int value ).

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM