2010-10-16 35 views
2

我正在嘗試處理具有多個附件的彩信。對於我正在創建一個HashMap如下(這不是完全實現,但只有相關部分):HashMap - 正確的用法?

HashMap<String, Integer> hashAttachments = new HashMap<String, Integer>(); 
    int c = 0; 
    if(atts != null) { 
     for(Attachment a : atts){ 
      if(a.mimeType.startsWith("image/")){ 
          <some code here> 
       hashAttachments.put(a.fileName, indx); 
      }else if(a.mimeType.startsWith("text/")){ 
       <some code here> 
       hashAttachments.put("text_"+String.valueOf(c++)+".txt",indx); 
      } 
        <some more mime types> 
     } /* for */ 

我試圖處理郵件有附件4 - 兩個圖像和兩個文本,所以我當for循環結束時,希望哈希映射包含4個條目。

我實際上看到的是,在某些時候地圖上的一個條目被覆蓋,我最終得到3個條目而不是4.可能是什麼原因? (鑰匙都是獨一無二的,不爲空,而不是空在所有情況下)編輯

在此先感謝

:每次迭代按鍵後(看起來很完美,不是我所看到的檢查調試器鍵):

10-16 21:50:01.207: INFO/System.out(27593): ~~~~~~~ 
10-16 21:50:01.207: INFO/System.out(27593): abc.jpg 
10-16 21:50:01.207: INFO/System.out(27593): ~~~~~~~ 
10-16 21:50:01.217: INFO/System.out(27593): abc.jpg 
10-16 21:50:01.217: INFO/System.out(27593): 2010-06-18_12.47.50.jpg 
10-16 21:50:01.227: INFO/System.out(27593): ~~~~~~~ 
10-16 21:50:01.227: INFO/System.out(27593): abc.jpg 
10-16 21:50:01.227: INFO/System.out(27593): 2010-06-18_12.47.50.jpg 
10-16 21:50:01.227: INFO/System.out(27593): text_0.txt 
10-16 21:50:01.237: INFO/System.out(27593): ~~~~~~~ 
10-16 21:50:01.237: INFO/System.out(27593): abc.jpg 
10-16 21:50:01.237: INFO/System.out(27593): text_1.txt 
10-16 21:50:01.237: INFO/System.out(27593): 2010-06-18_12.47.50.jpg 
10-16 21:50:01.237: INFO/System.out(27593): text_0.txt 
+0

你顯示的內容,'塊中有什麼不對? – 2010-10-16 19:17:06

+0

哪個附件條目在HashMap中被覆蓋?只是爲了縮小它。 – 2010-10-16 19:19:58

+0

@Mark:有些代碼是一些與HashMap問題無關的代碼 - 我可以將它註釋掉,問題仍然存在 – Asahi 2010-10-16 19:23:09

回答

2

根據您時間戳的調試輸出是正確,請記住以下,對於HashMap類:

這個類並沒有瓜拉尼T恤關於地圖的順序;特別是,它不能保證訂單會隨着時間的推移保持不變。

從的Javadoc:http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html

在調試程序,它可能看起來像一個鍵/值對正被改寫,但在現實中,插入可能改變HashMap中的順序。測試put(...)的返回值是測試新鍵/值是否與現有鍵相沖突的最佳方法。

+0

謝謝,就是這樣! – Asahi 2010-10-16 20:17:05