我正在编写一个方法,该方法允许我计算字符串类型的元素在字符串类型的 LinkedList 中出现的次数。我下面显示的代码不起作用。在我下面评论的行中,我一直在获取索引越界。似乎找不到错误
public int findDuplicate (LinkedList<String> e) {
int j = 1;
LinkedList<String> test = e;
while (!test.isEmpty()){
test = e;
String value = test.pop();
//Screws up here when i = 6
for(int i =0; i<=test.size() && test.get(i)!=null; i++){
String value3 = test.get(i);
if(e.get(i).equals(value) && i<=test.size()){
String value2 = test.get(i);
j++;
String Duplicate = e.get(i);
e.remove(i);
}
}
System.out.println(value + " is listed " + j + " times");
}
return j;
}
使用 hashmaps.. 仍然不起作用
public void findDuplicate (LinkedList e) {
Map<String,Integer> counts = new HashMap<String,Integer>();
while(!e.isEmpty()){
String value = e.pop();
for(int i =0; i<e.size(); i++){
counts.put(value, i);
}
}
System.out.println(counts.toString());
}
我的代码应该遍历链表找出列表中的元素出现了多少次并同时从列表中删除重复项。然后打印元素及其在列表中出现的次数。我昨晚发布了这个,但还没有得到回复。抱歉重新发布。
最佳答案
您快跑到列表的末尾了。改变
for(int i =0; i<=test.size() && test.get(i)!=null; i++){
到
for(int i =0; i< test.size() && test.get(i)!=null; i++){
List
(或数组)的有效索引为 0
到 size() - 1
。
关于java - 使用 HashMaps Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15211626/