Reputation: 9065
I want to change the key of a specific origin key name of a map, and I want to find a way to modify it just in place, so that it will not copy things around while doing it. I already know that I can only delete a entry of the map through iterate using only a Iterator
. But when I put things back to the map while iterating the map. It can't be done. Anyway, I will put my sample code below, hope some one could give me a hint of doing this.
public class TestMapModify {
public static void main(String[] argvs){
Map<String, Object> m = new HashMap<String, Object>();
m.put("a",1);
m.put("b",2);
for(Iterator<Map.Entry<String, Object>> it = m.entrySet().iterator();it.hasNext();){
Map.Entry<String, Object> entry = it.next();
if(entry.getKey().equals("a")){
m.put("c", entry.getValue());
it.remove();
}
}
System.out.println(m);
}
}
On the above code, I want to change the key "a"
to "c"
and leaving it's value unmodified. But this code snippet will give a exception:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.remove(HashMap.java:944)
at me.armnotstrong.TestMapModify.main(TestMapModify.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
EDIT
I am aware that what cause this problem, but I want to find the "best" or alternative way to do that.
Upvotes: 0
Views: 434
Reputation: 4692
@Durandal has already answered this answer. I didn't read it earlier.
You can put new values into another map and then add it to existing map after iteration.
public class TestMapModify {
public static void main(String[] argvs) {
Map<String, Object> m = new HashMap<String, Object>();
Map<String, Object> anotherMap = new HashMap<String, Object>();
m.put("a", 1);
m.put("b", 2);
for (Iterator<Map.Entry<String, Object>> it = m.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
if (entry.getKey().equals("a")) {
anotherMap.put("c", entry.getValue());
it.remove();
}
}
m.putAll(anotherMap);
System.out.println(m);
}
}
Upvotes: 1