0

I'm encountering something weird to me and I can't get what is going on. I'm creating a HashMap, then adding some key-value pairs over a loop.Inside the loop i'm changing a pre-initialized array on every iteration. So what I expect is always different arrays as values in the map.Here's the code:

int[] valueArray = new int[3];
int key = 0;
Map<Integer, int[]> map = new HashMap<>();
while (key < 5) {
    for (int i = 0; i < 3; i++) {
        valueArray[i] = key;
    }
    System.out.println(Arrays.toString(valueArray));
    map.put(key, valueArray);
    key++;
}
for (int i = 0; i < map.size(); i++) {
    System.out.println("Key: " + i + " Value: " + Arrays.toString(map.get(i)));
}

And here's the output:

[0, 0, 0]
[1, 1, 1]
[2, 2, 2]
[3, 3, 3]
[4, 4, 4]
Key: 0 Value: [4, 4, 4]
Key: 1 Value: [4, 4, 4]
Key: 2 Value: [4, 4, 4]
Key: 3 Value: [4, 4, 4]
Key: 4 Value: [4, 4, 4]
Barney
  • 2,355
  • 3
  • 22
  • 37

1 Answers1

0

You are using same array ref every time. to make it work create a new ref on each iteration. like this :

int key = 0;
Map<Integer, int[]> map = new HashMap<>();
while (key < 5) {
int[] valueArray = new int[3];
    for (int i = 0; i < 3; i++) {
        valueArray[i] = key;
    }
    System.out.println(Arrays.toString(valueArray));
    map.put(key, valueArray);
    key++;
}
for (int i = 0; i < map.size(); i++) {
    System.out.println("Key: " + i + " Value: " + Arrays.toString(map.get(i)));
}
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45