【问题标题】:Is there a way to change the key of a map in-place with java?有没有办法用java就地更改地图的键?
【发布时间】:2015-04-21 10:19:48
【问题描述】:

我想更改地图的特定源键名称的键,并且我想找到一种方法来就地修改它,这样它就不会在这样做时复制东西。我已经知道我只能通过使用 only Iterator 进行迭代来删除地图的条目。但是当我在迭代地图时把东西放回地图时。这是不可能的。无论如何,我会把我的示例代码放在下面,希望有人能给我一个提示。

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);
    }
}

在上面的代码中,我想将键 "a" 更改为 "c" 并保持其值不变。但是这段代码sn-p会报异常:

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)

编辑

我知道导致此问题的原因,但我想找到“最佳”或替代方法。

【问题讨论】:

标签: java dictionary


【解决方案1】:

@Durandal 已经回答了这个答案。之前没看过。

您可以将新值放入另一个地图中,然后在迭代后将其添加到现有地图中。

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);
    }
}

【讨论】:

  • 似乎这是迄今为止最好的选择,我会接受这个,也感谢@Durandal。
猜你喜欢
  • 2016-03-25
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 2020-02-29
  • 2020-03-01
  • 1970-01-01
  • 2016-06-15
  • 2016-09-23
相关资源
最近更新 更多