0

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

3 Answers 3

5

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Since he is using exObj only as the value, not as the key, in the HashMap, it's not really necessary to override hashCode and equals.
2

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.

2 Comments

Got it--I didn't realize all of the objects shared static variables!
@quannabe That's the point of static fields. It's best not to use them with mutable data.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.