我正在尝试处理带有多个附件的彩信。为此,我创建了一个 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 个条目。
我实际看到的是,在某些时候 map 的一个条目被覆盖,我最终得到 3 个条目而不是 4 个。可能是什么原因? (键是唯一的,在所有情况下都不为空且不为空)
提前致谢
编辑:每次迭代后设置 key (看起来很完美,不是我在调试器中检查 key 时看到的):
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
最佳答案
基于您带时间戳的调试输出是正确的,请记住以下关于 HashMap 类的内容:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
来自 javadoc:http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html
在调试器中,它可能看起来像是键/值对被覆盖,但实际上,插入可能改变了 HashMap 的顺序。测试 put(...) 的返回值是测试新键/值是否与现有键冲突的最佳方法。
关于java - HashMap - 正确用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3950366/