2013-03-04 70 views
1

我正在寫一個方法,它允許我計算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()); 
} 

我的代碼應該通過鏈表找出多少次出現在列表中的元素工作並同時從列表中刪除重複項。然後打印元素及其出現在列表中的次數。我昨晚發佈了這個消息,但沒有得到答覆。對不起,轉發。

回答

2

關於你的HashMap的例子來算重複:

@Test 
public void countOccurrences() { 
    LinkedList<String> strings = new LinkedList<String>(){{ 
     add("Fred"); 
     add("Fred"); 
     add("Joe"); 
     add("Mary"); 
     add("Mary"); 
     add("Mary"); 
    }}; 

    Map<String,Integer> count = count(strings,new HashMap<String,Integer>()); 
    System.out.println("count = " + count); 
} 

private Map<String, Integer> count(List<String> strings, Map<String, Integer> runningCount) { 
    if(strings.isEmpty()) { 
     return runningCount; 
    } 
    String current = strings.get(0); 
    int startingSize = strings.size(); 
    while(strings.contains(current)) { 
     strings.remove(current); 
    } 
    runningCount.put(current, startingSize - strings.size()); 
    return count(strings,runningCount); 
} 

如果你想保留了原始字符串列表,你可以做

Map<String,Integer> count = count(new LinkedList<String>(strings),new HashMap<String,Integer>()); 
    System.out.println("strings = " + strings); 
    System.out.println("count = " + count); 
6

您正在使用列表的末尾。改變

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(或陣列)是通過0size() - 1

1

這不會影響您的越界問題,但您仍然在評估它時從列表中刪除元素。如果刪除了一個元素,則應該在之後調用i--,否則您會跳過下一個實體(已重新編制索引)以供評估。

還有關於您的代碼的說明,我看到您正在嘗試複製您的列表,但標準分配意味着teste都指向相同的實例。您需要使用Collections.copy()請參閱this SO thread on how to use the class

1

我希望你明白什麼test = e語句做。在執行這個語句之後,teste參考相同的對象。

如果其中任何人修改列表,另一個人看到它,因爲他們都在看同一個對象。

如果這不是你的意圖,你需要克隆列表將其分配給另一個列表引用之前。