今天遇到了比较两个map中的值能否一致的问题,具体是前台传一个json字符串,我将其转换成map,之后与数据库中的map进行比对。
public static void main(String[] args) { Map<Integer,Integer> map1 = new HashMap<>(); map1.put(1,3); map1.put(2,3); map1.put(3,4); Map<Integer,Integer> map2 = new HashMap<>(); map2.put(1,3); map2.put(3,4); map2.put(2,3); System.out.println(map1.equals(map2)); }
看了一下jdk源码,恍然大悟
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 { Iterator<Entry<K,V>> i = entrySet().iterator(); while (i.hasNext()) { Entry<K,V> e = i.next(); 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;}