简体   繁体   English

Java:HashMap中的对象作为值被覆盖吗?

[英]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: 首先,我的(不好称呼的)hashmap类:

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: 第二,我简单的exObj类别:

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 ). 尝试将您的类更改为具有实例数据(即,只需删除static in private int value )。

This is because value in your class exObj is static : 这是因为类exObj valuestatic

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. 因为它是static ,所以变量只有一个副本,所有exObj对象都共享该副本。

See Understanding Instance and Class Members . 请参阅了解实例和类成员

As @Jeff Foster and @Jesper said, it's all about using a static variable. 正如@Jeff Foster和@Jesper所说,这都是关于使用静态变量的。 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. 最后一个初始化的exObj获得值'9',所有实例都共享该值。 Then by calling 然后致电

hm.get(2).setValue();

the value is set as '10' 该值设置为“ 10”

You can simply declare the 'value' as 您可以简单地将“值”声明为

private int value;

so every instance of exObj will have it's own value. 因此,exObj的每个实例都将具有自己的价值。 Also remember to have your Class names starting with a capital letter, as a good practice 另外,请记住,以良好的做法将班级名称以大写字母开头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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