我在寫一個方法,它允許我計算String類型的元素在Strings類型的LinkedList中出現的次數。我的代碼如下所示,不起作用。我一直在索引超出我在下面評論的行。似乎無法找到的bug元素顯示在鏈表中的計數次數Java
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;
}
使用包含HashMap ..仍然無法正常工作 公共無效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());
}
'我
Leri
2013-03-04 07:35:24