日期:2014-05-20  浏览次数:20635 次

比较两个map中的key value,有什么简便的方法或思路?
RT:比较两个map中的key value,有什么简便的方法或思路?
         假如拿map2与map1做比较;实现
          map1和map2中存在完全相同的key和value则返回true

          map1包含map2中的key和value也返回true

          map1不包含map2中的key返回false 并打印该key和value


------解决方案--------------------
	public static boolean compareMap(Map map1, Map map2) {
boolean contain = false;
for (Object o : map1.keySet()) {
contain = map2.containsKey(o);
if (contain) {
contain = map1.get(o).equals(map2.get(o));
}
if (!contain) {
return false;
}
}
return true;
}

仅限基础数据类型的map集合,对象类型需要重写equals和hashcode
------解决方案--------------------
Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Overrides: equals(...) in Object
Parameters:
o object to be compared for equality with this map


map的equals方法说的很明白了。
------解决方案--------------------
直接循环比较吧。

或者重写equals方法,吧key和value都比较下,都相同返回true,否则返回false