Bryce Hahn
Bryce Hahn

Reputation: 1773

java hashmap overwriting values

I'm trying to use a hashmap to store an int array of 4 integers. when I add to the hashmap it is supposed to add the most recent set of 4 integers and then generate a new set of 4 numbers. But instead it overwrites all values with the newly generated set of 4 integers... This seems weird since I never tell it to do so. Any ideas? Here is the code where it gets added

System.out.println("Games Played: " + gamesPlayed);
System.out.println("Size Before: " + scoreAnswer.size());
scoreAnswer.put(gamesPlayed, answer); //gamesPlayed will increase by 1 every time right after
System.out.println("Size After: " + scoreAnswer.size());
for (int i = 0; i < maxPin; i++) {
    System.out.println(answer[i]);
}
System.out.println("hash");
for (int i = 0; i < scoreAnswer.size(); i++) {
    int[] a = scoreAnswer.get(i);
    for (int j = 0; j < a.length; j++) {
        System.out.println("[" + i + "]"  + a[j]);
    }
}
gamesPlayed++;
System.out.println("Games Played: " + gamesPlayed);

when I run the program and have it add to the hashmap this is what will print out:

Games Played: 0, Size Before: 0, Size After: 1, 4 0 0 4, hash [0]4 [0]0 [0]0 [0]4 Games Played: 1

Everything is working here, untill i have it add another to the hash, it will then return this:

Games Played: 1, Size Before: 1, Size After: 2, 4 2 0 4, hash [0]4 [0]2 [0]0 [0]4 [1]4 [1]2 [1]0 [1]4, Games Played: 2

As you can see, the first set of integers have been overwritten to the 2nd set of integers. I have no idea why this is happening. Any help is appreciated!

EDIT: So sorry, my computer posted the question before I was finished typing all of my code.

Upvotes: 1

Views: 474

Answers (1)

John Ding
John Ding

Reputation: 1350

Based on your code, the variable "answer" must be the array you want to put into the hashmap, I guess you need to initialize it every time using the new keyword, like this

int[] answer = new int[4];

Upvotes: 3

Related Questions