代码之家  ›  专栏  ›  技术社区  ›  Asahi

哈希映射-正确用法?

  •  2
  • Asahi  · 技术社区  · 14 年前

    我正在尝试处理带有多个附件的彩信。为此,我创建了一个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
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   robert_x44    14 年前

    基于您的时间戳调试输出是正确的,请记住以下关于HashMap类的内容:

    从javadoc: http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html

    在调试器中,它可能看起来像一个键/值对被覆盖,但实际上,插入可能改变了HashMap的顺序。测试put(…)的返回值是测试新键/值是否与现有键冲突的最佳方法。