2013-12-08 14 views
0

我正在尝试存储一条单词在推文流中的总使用次数。每收到一条推文,我都会将它分成一个数组,然后迭代数组以将每个单词添加到hashmap,或者如果它已经存在,则增加它的值。我的问题是,每次收到推文时hashmap都显示为空白。每当我添加一组新数据时Java Hashmap会被清除

private HashMap<String, Integer> map; 

private void createDataStore() { 
    map = new HashMap<String, Integer>(); 
} 

protected void addKeywords(Status status) { 
    // get tweet 
    String str = status.getText(); 
    // split into an array 
    String[] splited = str.split("\\s+"); 
    // vars used in loop 
    String thisStr; 
    int wordTot; 

    for (int i = 0; i < splited.length; i++) { 
     // get word from array 
     thisStr = splited[i]; 
     // check if the word is in the hashmap 
     if (!map.containsKey(thisStr)) { 
      // already exists 
      map.put(thisStr, 1); 
     } else { 
      // its a new word! 
      wordTot = map.get(thisStr); 
      wordTot++; 
      map.put(thisStr, wordTot); 
     } 

    } 

} 

private void traceTotals() { 
    System.out.println("trace totals"); 

    Iterator<Entry<String, Integer>> it = map.entrySet().iterator(); 
    while (it.hasNext()) { 
     Map.Entry pairs = (Map.Entry) it.next(); 
     System.out.println(pairs.getKey() + " = " + pairs.getValue()); 
     it.remove(); // avoids a ConcurrentModificationException 
    } 

} 
+4

你如何使用这个代码由iterator.this语句返回的最后一个元素删除集合中删除?你是否为每条推文调用'createDataStore'? –

+0

你怎么称呼这三种方法? – Masudul

+0

当然与'HashMap'无关。这种行为主要依赖于方法调用序列和“状态”的内容。只需在'addKeywords()'和'createDataStore()'中添加额外的日志记录,你就会发现问题出在哪里。 –

回答

1

it.remove();实际上从HashMap中删除条目。调用it.remove();不需要遍历Collection,它只能用于删除元素。

0

看来,it.remove();造成这种情况。我评论过这一行,代码工作正常。

任何人都可以解释发生了什么? 谢谢!

+0

感谢您的快速回复。 createDataStore()仅被调用一次。每次接收到推文时都会调用addKeywords(),并在之后立即调用traceTotals()以显示新数据。 – alidrongo

+3

你的'traceTotals()'带'remove()'存在有效地清除了你的地图。 –

+1

看起来你在接收到每条推文后,在遍历地图并删除其中的每一条记录之后调用'traceTotals'。这可以解释为什么当下一个推文发布时地图是空的。 – A4L

0

it.remove()从底层集合

相关问题