【问题标题】:Can I trust HashMap iterator order? [duplicate]我可以信任 HashMap 迭代器顺序吗? [复制]
【发布时间】:2019-12-25 10:24:18
【问题描述】:

我想比较 2 个 HashMap 对象,并且我想迭代值 Collection,类似于 this answer

但是我可以确定 2 对象迭代器会按照相同的顺序运行吗?

如果没有,我考虑下一个,但它不那么好看:

public class MyObject {
    HashMap<Integer, String> myMap = new HashMap<Integer, String>();

    @Override
    public boolean equals(Object obj) {
        if(!(obj instanceof MyObject))
            return false;

        MyObject other = (MyObject)obj;

        if(this.myMap.size() != other.myMap.size())
            return false;

        for (Iterator<Entry<Integer, String>> it = myMap.entrySet().iterator(); it.hasNext(); ) {
            Entry<Integer, String> entry = it.next();
            String otherValue = other.myMap.get(entry.getKey());
            if(otherValue == null || !entry.getValue().equals(otherValue))
                return false;
        }
        return true;
    }
}

【问题讨论】:

  • 我可以确定 2 对象迭代器会按照相同的顺序运行 不,你不能。地图或未订购。
  • 为什么不使用JDK实现呢? this.myMap.equals(other.myMap)
  • 确实,使用JDK实现。一方面,如果两个映射中相同键的值是null,它们应该被认为是相等的,你的返回false。
  • 相同值的顺序不同的示例: 将两个条目添加到地图:map.put(654321, "A"); map.put(123456, "B");。对两个不同的地图执行此操作:new HashMap&lt;&gt;(2)new HashMap&lt;&gt;(16)。打印结果。顺序会有所不同。在 OpenJDK 13 上测试。
  • @Eran,这是我对课程的第一个想法。但是我在线阅读了HashMap并没有覆盖equals函数,因此它调用了Object one。

标签: java hashmap


【解决方案1】:

如果您也想比较插入顺序,请使用LinkedHashMap

代替

HashMap<Integer, String> myMap = new HashMap<Integer, String>();

使用

Map<Integer, String> myMap = new LinkedHashMap<>();

【讨论】:

  • 这没有错,但LinkedHashMap 也不是“有序”(即基本上“可索引”),它只是保留了插入顺序。
猜你喜欢
  • 2019-01-16
  • 2018-08-08
  • 1970-01-01
  • 2015-05-28
  • 2012-09-30
  • 2019-01-15
  • 1970-01-01
  • 2019-03-18
  • 2015-08-27
相关资源
最近更新 更多