0

I created a HashMap class with some methods. Then I'm creating an object of this class (objectA) and putting an array into it. And then I'm extracting this array to do some changes with it and putting changed array into new objectB. But with changing extracted array, my objectA has changed too! Why this happening?

Here is full working example:

public class MyClass extends LinkedHashMap<String, int[]> {

public static void main(String[] args) {
    MyClass objectA = new MyClass();
    objectA.put("somekey", new int[]{1,2,3});
    System.out.println(Arrays.toString(objectA.get("somekey"))); // [1,2,3]
    MyClass objectC = objectA.myMethod(); // I did nothing with my objectA
    System.out.println(Arrays.toString(objectA.get("somekey"))); //[0,10,20]    but objectA has changed! 

}

public int[] getValues(String key){
    int[] result = this.get(key);
    return result;
}

public void putValues(String key, int[] values){
    this.put(key, values);
}

public MyClass myMethod(){
    MyClass objectB = new MyClass();
    //getting array from hashmap
    int[] values = this.getValues("somekey");
    //now I'm changing the array
    for (int i=0; i<values.length; i++){
        values[i] = i*10;
    }
   // and my objectA(this) has been changed!
   objectB.put("anotherkey", values);

    return objectB;
}

}
Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
Andrei Sh
  • 113
  • 1
  • 11

2 Answers2

2

The behavior is because in Java every object holds the reference, not the value. So, in your case

objectA.put("somekey", new int[]{1,2,3});

a reference is stored of the int array.

Then, when you calling the objectA.myMethod(), in myMethod() you are getting the same reference of the array.
Then you have modified the same array and putted back with anotherkey key which is still having the same reference.

Therefore, your objectA.get("somekey") has changed.

For more info check this question: Is Java "pass-by-reference" or "pass-by-value"?

Community
  • 1
  • 1
Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
1

Your for loop is directly modifying the array of integers stored in objectA. You can get the desired behavior by making a copy of the array:

public MyClass myMethod(){
    MyClass objectB = new MyClass();

    int[] values = this.getValues("somekey");
    int[] temp = Arrays.copyOf(values, values.length);

    for (int i=0; i<values.length; i++){
        temp[i] = i*10;
    }

    objectB.put("anotherkey", temp);

    return objectB;
}
Andrew Jenkins
  • 1,590
  • 13
  • 16