我正在编写一个方法,允许我计算String类型的元素在String类型的LinkedList中出现的次数.我的代码如下所示不起作用.我继续在下面评论的行中获得索引超出界限.似乎无法找到这个bug
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;
}
Run Code Online (Sandbox Code Playgroud)
使用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());
}
Run Code Online (Sandbox Code Playgroud)
从使用方式看起来很清楚,test并且e您希望它们是两个独立的独立对象.事实上,他们不是.执行以下任务时:
test = e;
Run Code Online (Sandbox Code Playgroud)
两者test并e最终指向同一个列表.当你换一个时,它们都会改变.
至于解决问题的好方法,您可能希望使用a Map<String,Integer>来计算每个唯一字符串在列表中出现的次数.然后,您可以只对列表进行一次迭代,填充地图.最后,地图将给出最终计数.
| 归档时间: |
|
| 查看次数: |
601 次 |
| 最近记录: |