繁体   English   中英

java.util.HashMap ----看一下控制台,为什么打印顺序是这样的

[英]java.util.HashMap----look the console, why the print order is like this

今天,我研究了从java.util.HashMap中删除特殊对象的方法。 我测试了错误的语法。 但是我遇到了一个奇妙的问题。 控制台上的消息顺序不正确。 异常消息按错误的顺序打印。 该程序似乎以多线程执行。 以下是我的代码。

package com.study.iter;

import java.util.HashMap;
import java.util.Map;

public class TestRmObjFromMap {

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap();

        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);
        map.put("4", 4);

        remove1(map);
    }

    private static void remove1(Map<String, Integer> map) {

        for(Map.Entry<String, Integer> entry : map.entrySet()) {

            if(entry.getKey().equals("3")) {
                map.remove(entry.getKey());
            }
            else {
                System.out.println("key: " + entry.getKey() + " -- value: " + entry.getValue());
            }

        }

    }

}

运行此代码后,它将打印以下内容:

Exception in thread "main" java.util.ConcurrentModificationException
key: 1 -- value: 1
key: 2 -- value: 2
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1437)
    at java.util.HashMap$EntryIterator.next(HashMap.java:1471)
    at java.util.HashMap$EntryIterator.next(HashMap.java:1469)
    at com.study.iter.TestRmObjFromMap.remove1(TestRmObjFromMap.java:29)
    at com.study.iter.TestRmObjFromMap.main(TestRmObjFromMap.java:24)

为什么将异常消息除以其他消息。 为什么不这样:

key: 1 -- value: 1
key: 2 -- value: 2
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1437)
    at java.util.HashMap$EntryIterator.next(HashMap.java:1471)
    at java.util.HashMap$EntryIterator.next(HashMap.java:1469)
    at com.study.iter.TestRmObjFromMap.remove1(TestRmObjFromMap.java:29)
    at com.study.iter.TestRmObjFromMap.main(TestRmObjFromMap.java:24)

谁能告诉我原因? 谢谢!

现在是一个简单的测试:

public static void main(String[] args) {

    for(int i=0;i<500;i++) {
        System.out.println("ttt");
        if(i==10) throw new ConcurrentModificationException();
    }

}

结果:

Exception in thread "main" java.util.ConcurrentModificationException
    ttt
    at com.study.iter.TestIter.main(TestIter.java:14)
    ttt
    ttt
    ttt
    ttt
    ttt
    ttt
    ttt
    ttt
    ttt
    ttt

原因:

 Exceptions will printed at stderr and System.out.println prints on stdout. Both streams are not sychronized

谢谢!

异常将打印在stderr上,而System.out.println在stdout上打印。 两个流均未同步

在HashMap中,不能保证迭代顺序是插入顺序,即可以按其喜欢的任何顺序返回数据。

要使迭代顺序与插入顺序相同,请改用LinkedHashMap

例如

Map<String, Integer> map = new LinkedHashMap();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM