我有以下方法,我想比较2个HashMap :map1和map2。
每个HashMap都有:
key: string.
value: ArrayList<String>
我要做的是检查两个HashMaps是否相等
public boolean compareT(HashMap map1, HashMap map2) {
Iterator entriesH = map1.entrySet().iterator();
Iterator entriesE = map2.entrySet().iterator();
if (map1.size() == map2.size()) {
while (entriesE.hasNext() && entriesH.hasNext()) {
Map.Entry eEntry = (Map.Entry) entriesE.next();
Map.Entry hEntry = (Map.Entry) entriesH.next();
}
}
}
修改
以下地图应返回TRUE:
map1:
key: key1, value: v1, v6, v3, v2
key: key2, value: b1, b6, b2, b7
map2:
key: key1, value: v6, v3, v2, v1
key: key2, value: b6, b1, b7, b2
答案 0 :(得分:1)
我应该在比较它们之前订购每个键的值吗?
您的值为ArrayList
个对象。 ArrayLists(或任何其他List
实现)只有在相同的顺序具有相同的条目时才被认为是相同的。
也许您可以使用某种java.util.Set
代替。
答案 1 :(得分:0)
如果你永远不会得到map1.get(key).get(index)!= map2.get(key).get(index)那么你可以确定这些地图是一样的。
伪代码
if(map1.size == map2.size && map1.equals(map2))
//in here means the keys are the same
allkeys = map1's keys
for (string key : allKeys)
//now we need to loop through the arraylists
map1Arraylist = map1.get(key)
map2Arraylist = map2.get(key)
//check the sizes are the same if not return false right away
if(map1Arraylist.size != map2Arraylist.size) return false;
//if we got to here we now must check each index is the same
for(index = 0; index < map1Arraylist.size; index++)
//if a single index of the arraylists don't match up we return false
if(map1Arraylist.get(index) != map2Arraylist.get(index))
return false;
//if we get out of all the above logic then we have the same maps
return true;
else return false;