HashMap에서 항목을 제거하려고하면 Concurrent Modification Exception이 발생합니다. HashMap을 통해 반복하는 동안 항목을 제거하면이 예외가 트리거된다는 것을 알고 있지만 이전 항목을 새 항목으로 바꿔야합니다. 내가 어떻게 할 수 있니? 어쩌면 countNumberOfEachCharacter HashMap의 사본을 만들고, 원래 HashMap을 반복하여 사본 HashMap에서 항목을 제거하겠습니까?반복하는 동안 HashMap 항목 교체/변경
countNumberOfEachCharacter = new HashMap<Character,Character>();
if (countNumberOfEachCharacter.containsKey(word.charAt(i))) {
System.out.println("This character already exists");
for (Iterator it = countNumberOfEachCharacter.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
if (key.equals(word.charAt(i))) {
int toIncrease = Integer.parseInt(value.toString());
toIncrease++;
System.out.println("key "+key);
System.out.println("increased "+toIncrease);
countNumberOfEachCharacter.remove(word.charAt(i));
char c = Character.forDigit(toIncrease, 10);
countNumberOfEachCharacter.put(word.charAt(i),c);
}
}
}
else {
System.out.println("First time found this character");
char c = Character.forDigit(1, 10);
countNumberOfEachCharacter.put(word.charAt(i),c);
System.out.println("Stored "+word.charAt(i)+" with count "+c);
}
질문을보다 쉽게 읽을 수 있도록 시간을내어주십시오. –
'ConcurrentHashMap'을 사용하십시오. –
@ Eng.Fouad 동시 액세스가 없기 때문에 문제가 해결되지 않습니다. 그는 단지 그것을 반복하고 요소를 제거합니다. –