简体   繁体   English

java hashmap覆盖值

[英]java hashmap overwriting values

I'm trying to use a hashmap to store an int array of 4 integers. 我正在尝试使用hashmap来存储4个整数的int数组。 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. 当我添加到hashmap时,它应该添加最新的4个整数集,然后生成一组新的4个数字。 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. 但是它用新生成的4个整数集覆盖所有值......这看起来很奇怪,因为我从来没有告诉它这样做。 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: 当我运行程序并将其添加到hashmap时,这将打印出来:

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. 编辑:很抱歉,在我输入完所有代码之前,我的电脑发布了这个问题。

根据你的代码,变量“answer”必须是你想要放入hashmap的数组,我猜你每次使用new关键字时都需要初始化它,就像这样

int[] answer = new int[4];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM