根据这个问题:How to preserve insertion order in HashMap?
HashMap不保证 Map 的顺序;特别是,它不保证订单会随着时间的推移保持不变 .
但后来我有一个关于oracle教程的问题
public void updateCoffeeSales(HashMap<String, Integer> salesForWeek)
throws SQLException {
...
try {
...
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e ) {
...
} finally {
...
}
它来自这里:http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
他们怎么知道updateSales和updateTotal的值不会混合?
1 回答
该文档讨论了键值对的相对顺序 . 如果您添加项目
对于哈希映射,您可以在迭代时以任意顺序获取它们 . 例如,你可以得到
但是,这种重新排序无法打破对 . 换句话说,
a
将保持与b
配对 - 它不会被重新排序以对应于d
或f
.当您遍历 Map 的
entrySet()
时,您会得到一个无序的对列表 . 但是,对本身保持配对:如果为给定键设置了某个值,则无论迭代次序如何,它都将作为一对键返回 . 由于不应该依赖数据库表中项的自然顺序,因此特定的插入顺序没有区别 .