2012-08-27 3 views
1

에서의 HashMap의 조회 나는과 같이, 다차원 HashMaps을 가진 세트를 가지고 :자바 저장 및 HashSet의

Set<HashMap<String, HashMap<String, String>>> myHashSet = new HashSet<HashMap<String, HashMap<String, String>>>(); 

나는 문제는 HashMap의 항목을 제거하는 데. 최상위 해시 맵의 키를 알고 있지만 기본 해시 맵의 데이터를 모릅니다. 나는이 방법으로 세트의 해시 맵 항목을 제거하려고 :

I.

Set<HashMap<String, HashMap<String, String>>> myHashSet = new HashSet<HashMap<String, HashMap<String, String>>>(); 

... Add some hashmaps to the set, then ... 

String myKey = "target_key"; 
setInQuestion.remove(myKey); 

II.

Set<HashMap<String, HashMap<String, String>>> myHashSet = new HashSet<HashMap<String, HashMap<String, String>>>(); 

... Add some hashmaps to the set, then ... 

String myKey = "key_one"; //Assume a hashmap has been added with this top level key 
HashMap<String, HashMap<String, String>> removeMap = new HashMap<String, HashMap<String, String>>(); 
HashMap<String, String> dummyMap = new HashMap<String, String>(); 
removeMap.put(myKey, dummyMap); 
setInQuestion.remove(removeMap); 

이러한 방법 중 어느 것도 작동하지 않습니다. 최상위 해시 맵의 키만 알고있는 경우 집합의 항목을 제거하는 방법은 무엇입니까?

답변

2

Collection.remove()에는 객체 평등이 필요합니다. 다양한 jdk Map 구현은 모든 키/값이 일치해야 함을 의미하는 동등성을 구현합니다. remove() 호출에 전달하는 객체가 집합의 모든지도와 "동일"하지 않으므로 제거되는 것이 없습니다.

원하는 작업을 수행하는 유일한 방법은 Set을 반복하여 일치하는 Map을 찾거나 Set을 해당 특수 키가있는 Map으로 만듭니다.

0

안내를 위해 jtahlborn에게 감사드립니다. 대답의 결과로 찾은 해결책을 게시하고 싶습니다.

String myKey = "Key_In_Question"; 
Iterator mySetIterator = myHashSet.iterator(); 
while(mySetIterator.hasNext()) { 
    HashMap<String, HashMap<String, String>> entry = (HashMap<String, HashMap<String, String>>) mySetIterator.next(); 
    if(entry.containsKey(myKey)) { 
     myHashSet.remove(entry); 
    } 
} 
+0

실제로 ConcurrentModificationException이 발생합니다. 대신에,'mySetIterator.remove()'를 사용하십시오. – jtahlborn

0

죄송합니다. 의견을 게시 할 수 없습니다. 나는 약 Map 평등에 대한 @ jtahlborn의 지적이 계약의 잘 정의 된 부분이라고 지적하고 싶다 ... Map.equals을 참조한다.

...이 맵 m1m2는 같은 매핑 m1.entrySet().equals(m2.entrySet()) 경우를 나타냅니다. 이렇게하면 Map 인터페이스의 다른 구현에서 equals 메서드가 제대로 작동합니다.

Map.Entry.equals도 마찬가지입니다.

 (e1.getKey()==null ? 
     e2.getKey()==null : e1.getKey().equals(e2.getKey())) && 
     (e1.getValue()==null ? 
     e2.getValue()==null : e1.getValue().equals(e2.getValue())) 

이것은 equals 방법은 Map.Entry 인터페이스의 다양한 구현으로 적절히 동작하는 것이 보증하는 경우

... 두 항목 e1e2는 같은 매핑을 나타냅니다.

관련 문제