【发布时间】:2016-02-05 12:20:15
【问题描述】:
我遇到了一个非常奇怪的情况,其中一个 HashMap 变量
HashMap<Integer, String> locationCatalog = new HashMap<>();
将正确地迭代(即从第一个数字键开始),有时它不会。我正在遍历 Excel 文档(使用外部库)以获取单元格值,并根据单元格的不同,根据单元格的行和列坐标将其放入 HashMap。
locationCatalog.put(row.getRowNum(), cell.getStringCellValue().trim());
填充完所有数据后,我遍历 locationCatalog 以获取内容:
Set set = locationCatalog.entrySet();
Iterator trimIterator = set.iterator();
System.out.println(lastLabelName + " - locationCatalog contents (run #1):");
while (trimIterator.hasNext()) {
Map.Entry locationMap = (Map.Entry)trimIterator.next();
System.out.println("Key: " + (int) locationMap.getKey() + ", Row: " + ((int) locationMap.getKey() + 1) + ", Location: " + locationMap.getValue().toString());
...
}
这是一个良好运行的打印结果:
BALI - locationCatalog contents (run #1):
Key: 16, Row: 17, Location: S082025 E1150531
Key: 17, Row: 18, Location: S082025 E1150531
Key: 18, Row: 19, Location:
Key: 19, Row: 20, Location: S082025 E1150531
Key: 20, Row: 21, Location:
Key: 21, Row: 22, Location: S082025 E1150531
异常偶尔发生。当我移动一个单元格而不是仅仅复制和粘贴内容时,它似乎就开始了。一旦我弄清楚了,我调整了 put 方法,只使用一个独立于 Excel 源的常规整数。然而,这一调整并没有改变结果。这是一个糟糕的运行示例:
BALI - locationCatalog contents (run #1):
Key: 16, Row: 17, Location: S08 20 25 E115 05 31
Key: 17, Row: 18, Location:
Key: 18, Row: 19, Location:
Key: 9, Row: 10, Location: S08 20 25 E115 05 31
Key: 10, Row: 11, Location: S08 20 25 E115 05 31
Key: 11, Row: 12, Location:
Key: 12, Row: 13, Location: S08 20 25 E115 05 31
Key: 13, Row: 14, Location:
Key: 14, Row: 15, Location: S08 20 25 E115 05 31
Key: 15, Row: 16, Location: S08 20 25 E115 05 31
由于无法发布 Excel 文件的屏幕截图,此运行的单元格从第 10 行开始并一直持续到第 19 行。但是,当它通过 locationCatalog 的迭代时,它不会从最低键开始,在这种情况下,键 9。这是一个问题,因为我必须多次遍历此 HashMap 才能获得最终产品,并且需要按升序排列。完成收集后,我将其清除以开始使用一组新数据填充它。
如果我将相同的单元格剪切并粘贴到不同的行中,结果(正确)会变为:
BALI - locationCatalog contents (run #1):
Key: 4, Row: 5, Location: S08 20 25 E115 05 31
Key: 5, Row: 6, Location: S08 20 25 E115 05 31
Key: 6, Row: 7, Location:
Key: 7, Row: 8, Location: S08 20 25 E115 05 31
Key: 8, Row: 9, Location:
Key: 9, Row: 10, Location: S08 20 25 E115 05 31
Key: 10, Row: 11, Location: S08 20 25 E115 05 31
Key: 11, Row: 12, Location: S08 20 25 E115 05 31
Key: 12, Row: 13, Location:
Key: 13, Row: 14, Location:
我已经尝试了一周来弄清楚发生了什么,包括更改 HashMap 的参数,但都没有运气。希望有更多智慧和 Java 专业知识的人可以伸出援助之手。
【问题讨论】: