我正在寫一個方法,它允許我計算String類型的元素在Strings類型的LinkedList中出現的次數。我的代碼如下所示不起作用。我一直在索引超出我在下面評論的行。似乎無法使用包含HashMap找到錯誤使用HashMaps 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;
}
..仍然沒有
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());
}
我的代碼應該通過鏈表找出多少次出現在列表中的元素工作並同時從列表中刪除重複項。然後打印元素及其出現在列表中的次數。我昨晚發佈了這個消息,但沒有得到答覆。對不起,轉發。