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;
}
}