比较两张地图

noM*_*MAD 60 java dictionary

我有两个声明为的地图Map<String, Object>.在Object这里可以是另一个Map<String, Object>(依此类推).我想在不知道它们的深度的情况下检查两个地图是否完全相同.我可以比较toString()每个地图上被调用的输出而不是使用递归吗?或者是否有更简单的方法来比较地图?

Men*_*los 64

快速回答

您应该使用该equals方法,因为这是为了执行您想要的比较.toString()它本身使用迭代器,equals但它是一种效率更低的方法.另外,正如@Teepeemm指出的那样,toString受元素顺序(基本上是迭代器返回顺序)的影响,因此不能保证为2个不同的映射提供相同的输出(特别是如果我们比较两个不同的映射).

注意/警告:您的问题和我的答案假设实现地图界面的类尊重预期toStringequals行为.默认的java类这样做,但需要检查自定义映射类以验证预期的行为.

请参阅:http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)
Run Code Online (Sandbox Code Playgroud)

将指定对象与此映射进行相等性比较.如果给定对象也是一个映射,并且两个映射表示相同的映射,则返回true .更正式地说,如果m1.entrySet().equals(m2.entrySet()),则两个映射m1和m2表示相同的映射.这可确保equals方法在Map接口的不同实现中正常工作.

Java Source(java.util.AbstractMap)中的实现

此外,java本身负责迭代所有元素并进行比较,因此您不必这样做.看一下AbstractMap类的使用实现,例如HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) 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;
    }
Run Code Online (Sandbox Code Playgroud)

比较两种不同类型的地图

toString比较a TreeMapHashMap虽然equals比较内容正确,但是失败了.

码:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}
Run Code Online (Sandbox Code Playgroud)

输出:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}
Run Code Online (Sandbox Code Playgroud)

  • 应该强调的是,即使两个映射都具有相同的类型,即它们都是HashMap,也不保证迭代顺序是相同的,因此,比较toString()结果将失败。遇到的顺序是一个实现细节,它取决于键的哈希码*和*当前容量(即使大小相同,也可能有所不同),此外,条目存储在同一数组元素中(又称为哈希冲突)链接的顺序取决于地图的“历史记录”,即插入顺序或是否删除了其他键等。 (2认同)

nic*_*are 11

只要覆盖equals()映射中包含的每个键和值,那么m1.equals(m2)应该可靠地检查映射是否相等.

通过比较toString()您建议的每个地图也可以获得相同的结果,但使用equals()是更直观的方法.

可能不是您的具体情况,但如果您在地图中存储数组,可能会有点棘手,因为它们必须按值或使用进行比较Arrays.equals().关于此的更多细节请参见此处.