【发布时间】: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<>(2)和new HashMap<>(16)。打印结果。顺序会有所不同。在 OpenJDK 13 上测试。 -
@Eran,这是我对课程的第一个想法。但是我在线阅读了HashMap并没有覆盖equals函数,因此它调用了Object one。