[英]HashMap wrong values for keys
I am kinda new to Java, and I am trying to write a function that maps all element indexes from an ArrayList into a HashMap, so I can easily see the indexes of duplicate elements. 我是Java的新手,我正在尝试编写一个将所有元素索引从ArrayList映射到HashMap的函数,因此我可以很容易地看到重复元素的索引。
The code below works , but when I try to print the values using the second for, it shows completely different results! 下面的代码有效,但是当我尝试使用第二个代码打印值时,它会显示完全不同的结果!
Example: 例:
60 [40, 64] 60 [40,64]
What the 2nd for shows 显示的第二个是什么
60 [64] 60 [64]
more numbers 更多数字
60 [64] 60 [64]
HashMap<Integer,ArrayList<Integer>> table= new HashMap<Integer,ArrayList<Integer>>();
//checking all items in an ArrayList a
//and putting their index in a hashTable
for(int i=0; i<a.size(); i++){
ArrayList<Integer> indexes = new ArrayList<Integer>();
indexes.add(i);
for(int j=i+1; j<a.size(); j++){
//are the items equal?
if(a.get(j).equals(a.get(i))){
indexes.add(j);
}
}
//put in the HashMap
table.put(a.get(i), indexes);
System.out.println(a.get(i) + " " +table.get((a.get(i))));
}
//shows completely different results!
for(int ix=1;ix<table.size();ix++)
System.out.println(a.get(ix) + " " +table.get(a.get(ix)));
Try this: 尝试这个:
public static void main(String[] args) {
List<Integer> input = Arrays.asList(60, 60, 1, 4, 5, 7, 60);
Map<Integer, List<Integer>> result = new HashMap<>();
for (int n = 0; n < input.size(); ++n) {
List<Integer> list = result.get(input.get(n));
if (list != null) {
list.add(n);
} else {
list = new ArrayList<>();
list.add(n);
result.put(input.get(n), list);
}
}
System.out.println(result); // prints {1=[2], 4=[3], 5=[4], 7=[5], 60=[0, 1, 6]}
}
But I don't get it...What did I do wrong?
但我不明白......我做错了什么? As far as I see, my code is really inefficient compared to yours, but shouldn't it do the same thing?
据我所知,我的代码与你的代码相比效率很低,但它不应该做同样的事情吗?
Well no. 好吧不。 In addition to being inefficient, your version has a significant bug.
除了效率低下之外,您的版本还有一个重要的错误。
Lets take your example input {60, 60, 1, 4, 5, 6, 7, 60}
. 让我们举例输入
{60, 60, 1, 4, 5, 6, 7, 60}
。
First iteration the loop, you build a list containing {0, 1, 7}
and put it into the map so that we have map containing
{ 60 -> {0, 1, 7} }` 首先迭代循环,你构建一个包含
{0, 1, 7}
的列表并将其放入地图中,这样我们就可以得到map containing
{60 - > {0,1,7}}的map containing
Second iteration of the loop, we build a list containing {1, 7}
and put it into the map. 循环的第二次迭代,我们构建一个包含
{1, 7}
的列表并将其放入地图中。 But this of course replaces the original (correct) list for 60
... and we end up with { 60 -> {1, 7} }
但这当然取代了
60
的原始(正确)列表...我们最终得到{ 60 -> {1, 7} }
And so on. 等等。 In short, your version will end up producing a map that maps from the values to a list containing just the last index of that value.
简而言之,您的版本将最终生成一个映射,该映射从值映射到仅包含该值的最后一个索引的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.