【发布时间】:2014-03-16 10:53:08
【问题描述】:
我对 Java 有点陌生,我正在尝试编写一个函数,将 ArrayList 中的所有元素索引映射到 HashMap,因此我可以轻松查看重复元素的索引。
下面的代码有效,但是当我尝试使用第二个 for 打印值时,它显示的结果完全不同!
例子:
60 [40, 64]
第二个是什么节目
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)));
【问题讨论】:
-
我不确定我是否理解您要完成的工作,因为单个
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 中作为值?
标签: java hashmap key key-value