1. 用equals 比较
public static void main(String[] args) {
List<Map<String,Object>> list = new ArrayList<>();
Map<String,Object> map1= new HashMap<>();
map1.put("name","郭");
map1.put("objId","1");
list.add(map1);
Map<String,Object> map2= new HashMap<>();
map2.put("name","郭2");
map2.put("objId","2");
list.add(map2);
//
Map<String,Object> map3= new HashMap<>();
map3.put("name","郭2");
map3.put("objId","2");
Map<String,Object> map4= new HashMap<>();
map4.put("name","郭3");
map4.put("objId","2");
// true
if(list.contains(map3)){
System.out.println("hhh");
}
// false
if(list.contains(map4)){
System.out.println("hhh");
}
// true(可以用来比较两个map 的key ,value 是否一样)
System.out.println(map2.equals(map3));
}
底层逻辑:
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<?,?> m = (Map<?,?>) o;
if (m.size() != size())
return false;
try {
for (Entry<K, V> e : entrySet()) {
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key) == null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}