Java HashMap键的值错误
我对Java有点陌生,我正在尝试编写一个函数,将ArrayList中的所有元素索引映射到HashMap中,这样我就可以很容易地看到重复元素的索引 下面的代码可以工作,但是当我尝试使用第二个for打印值时,它显示了完全不同的结果 例如: 60[40,64] 第二场是什么 60[64]Java HashMap键的值错误,java,hashmap,key,key-value,Java,Hashmap,Key,Key Value,我对Java有点陌生,我正在尝试编写一个函数,将ArrayList中的所有元素索引映射到HashMap中,这样我就可以很容易地看到重复元素的索引 下面的代码可以工作,但是当我尝试使用第二个for打印值时,它显示了完全不同的结果 例如: 60[40,64] 第二场是什么 60[64] HashMap<Integer,ArrayList<Integer>> table= new HashMap<Integer,ArrayList<Integer>>()
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)));
更多数字
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)));
HashMap table=newhashmap();
//检查ArrayList a中的所有项
//并将其索引放入哈希表中
对于(int i=0;i请尝试以下方法:
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]}
}
publicstaticvoidmain(字符串[]args){
列表输入=Arrays.asList(60,60,1,4,5,7,60);
映射结果=新的HashMap();
对于(int n=0;n
但我不明白…我做错了什么?据我所知,我的代码与你的相比确实效率低下,但它不应该做同样的事情吗
当然不是。除了效率低下之外,你的版本还有一个严重的错误
让我们以您的示例输入{60,60,1,4,5,6,7,60}
在循环的第一次迭代中,您构建了一个包含{0,1,7}
的列表,并将其放入映射中,这样我们就得到了包含{60->{0,1,7}的映射`
在循环的第二次迭代中,我们构建了一个包含{1,7}
的列表,并将其放入映射中。但是这当然会替换60
的原始(正确)列表…我们最终得到{60->{1,7}
以此类推。简而言之,您的版本最终将生成一个从值映射到仅包含该值的最后一个索引的列表的映射。我不确定我是否理解您试图实现的目标,因为单个ArrayList
的索引始终为[0,list.size()-1]。您可以指定您要实现的目标吗?我正在尝试映射ArrayList中所有元素的索引,以便可以轻松查看重复元素的索引。ArrayList的工作方式与常规数组类似,第一个索引为0,最后一个索引为(size-1)。您没有任何重复的索引。明白,但如果我有{60,60,1,4,5,6,7,60},我应该在HashMap 60[0,1,8]中你想要一个HashMap
,其中Arraylist的唯一值作为键,相应键的索引作为值保存在Arraylist中?它…有效!谢谢!!!但我不明白…我做错了什么?据我所知,我的代码与你的代码相比效率很低,但它不应该做同样的事情吗?我明白了。谢谢你的解释!