【发布时间】:2010-10-16 19:13:40
【问题描述】:
我正在尝试处理带有多个附件的彩信。为此,我正在创建一个 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 个。可能是什么原因? (键是唯一的,在所有情况下都不为空且不为空)
提前致谢
EDIT:每次迭代后设置的键(看起来很完美,不是我在调试器中看到的检查键):
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
【问题讨论】:
-
您显示的内容没有问题,
<some code here>块中有什么? -
HashMap 中哪个附件条目被覆盖?只是为了缩小范围。
-
尝试
System.out.println()输入您正在输入的密钥。这应该可以清楚地看出哪个被覆盖,因此您的问题是什么。 -
可以在每次迭代后打印
Map吗?从调试的角度来看,这会对我们有所帮助。 -
或者至少在调试器中单步执行时查看 put 的返回值。如果您要添加新键,则 put 的返回值应该为 null,但如果您要覆盖键的值,它将等于旧值。