ProgramingTip

두지도 비교

bestdevel 2020. 12. 5. 10:21
반응형

두지도 비교


두 개의지도가 Map<String, Object>. Object여기에 또 다른 수 Map<String, Object>(등 등). 두 맵이 깊이를 모르고 정확히 같은지 확인하고 싶습니다. 재귀를 사용하는 대신 각 toString()에서 호출 된 출력을 어디에 있습니까? 아니면 비교하는 더 간단한 방법이 있습니까?


빠른 답변

equals원하는 비교를 수행하기 위해 구현 합니다 . toString()자체적으로 반복적으로 사용 equals하지만 더 비효율적 인 접근 방식입니다. 또한 @Teepeemm이 지적했듯이 toString요소 순서 (기본적으로 반복기 반환 순서)의 영향 두 개의 다른 맵에 대해 동일한 출력을 제공하는 보장 할 수 없습니다 (두 개의 맵을 비교하는 경우).

참고 / 경고 : 귀하의 질문과 답변은 맵 인터페이스를 구현하는 클래스가 예상 toStringequals동작을 존중 가정합니다 . 기본 Java 클래스는 수행하지만 예상되는 동작을 확인 예상 사용자 정의 맵 클래스를 검사해야합니다.

참조 : http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

지도 된지도가 같은지 비교합니다. 목적지가지도되고 두지도 가 동일한 매핑을 사용한다면 true를 반환 합니다 . 보다 공식적으로 m1 및 m2 맵은 m1.entrySet (). equals (m2.entrySet ()) 인 경우 동일한 매핑을 나타냅니다 . 이렇게하면 메소드가 Map 인터페이스의 여러 구현에서 제대로 작동합니다.

자바 소스 (java.util.AbstractMap)에서 구현

또한 자바 자체가 모든 요소를 ​​반복하고 필요한 것이 처리됩니다. 다음 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;
    }

두 가지 다른 유형의지도 비교

toString비교할 때 비참을하게 실패 TreeMap하고 HashMap있지만 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());
}

다수 :

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

equals()지도에 포함 된 각 키와 값 재정의 하는 m1.equals(m2)한지도가 같은지 확인할 수 있습니다.

toString()대로 각지도 제안한를 비교해도 계명 동일한 결과를 얻을 수 있지만 사용하는 equals()것이 더 직관적 인 접근 방식입니다.

특정 상황이 아닐 수도 있지만 맵에 배열을 저장하는 경우 값별로 비교하거나 Arrays.equals(). 이에 대한 자세한 내용은 여기를 참조 하십시오 .

참고 URL : https://stackoverflow.com/questions/24814577/comparing-two-maps

반응형