我想比较 2 个 HashMap 对象,并且我想迭代值集合,比如 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;
}
}
最佳答案
如果您也想比较插入顺序,请使用LinkedHashMap
。
代替
HashMap<Integer, String> myMap = new HashMap<Integer, String>();
使用
Map<Integer, String> myMap = new LinkedHashMap<>();
关于java - 我可以信任 HashMap 迭代器顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59477432/