2012-05-16 30 views
1

散列表中的數據被同一個鍵覆蓋。我試圖在不同的時間間隔內對同一個鍵添加'n'個數據,明顯增加到散列表的數據被覆蓋,解決這個問題?在散列表中重寫數據

if (value == RepeatRule.DAILY) { 

          setHashRepeatData(repDates, eventBean, 
            listRepeatEvents); 

         } 
         if (value == RepeatRule.WEEKLY) { 

          setHashRepeatData(repDates, eventBean, 
            listWeekEvents); 
         } 

private void setHashRepeatData(Vector repDates, EventData eventBean, 
      Vector listOfRepeatData) { 

     if (repDates != null) { 
      System.out.println("the size of repDates is :" + repDates.size()); 
      System.out.println("summ" + eventBean.getSummary()); 
      listOfRepeatData.addElement(eventBean); 
      for (int i = 0; i < repDates.size(); i++) { 
       String currentRepDate = (String) repDates.elementAt(i); 
       System.out.println("currentRepDate" + currentRepDate); 

       listUserEvents.put(currentRepDate, listOfRepeatData); 

      } 
     } 

    } 

我打電話以不同的間隔上面的方法,並試圖設置相同key.I數據無法得到如何解決問題。

+0

這個環節上找到答案:http://stackoverflow.com/questions/1062960/map-implementation-with-duplicate-keys – rizzz86

回答

0

這將是你想要實現的,什麼樣的實現,如果你自己做:

// I took a set because I wanted have the inputs sorted 
HashMap<String, Set<String>> var = new HashMap<String, Set<String>>(); 

String key= "key"; 
String value = "value"; 

if(var.containsKey(key)){ 
// the set is already there we can proceed to add the value 
} else { 
    //first time you have to create the List 
    var.put(key, new TreeSet<String>()); 
} 
var.get(key).add(value); 

你將不得不相應地修改它以你的情況,如:

HashMap<String, Vector<String>> var = new HashMap<String, Vector<String>>(); 

String key= "key"; 
String value = "value"; 

if(var.containsKey(key)){ 
// the set is already there we can proceed to add the value 
} else { 
    //first time you have to create the List 
    var.put(key, new Vector<String>()); 
} 
var.get(key).addElement(value); 
+0

,在我的情況下,hashmap的值是vector,我只需要添加if循環? – harqs

+0

如何修改矢量圖,請讓我知道,因爲我找到完美的解決方案 – harqs

+0

好吧,您只需用一個應該做的矢量替換該集...因爲矢量圖具有相同的方法,所以應該添加其餘的工作...爲了創建列表,你還需要一個Vector。 – 2012-05-16 10:00:37

1

您正在查找多值地圖(對於同一個鍵,您可以有多個值)。

要麼你自己實現這個(通過將Map<K,V>更改爲Map<K,List<V>>),但對作者來說有點痛苦。

或者使用番石榴其提供的功能:Multimaps(我會推薦這種方法)