HashMap的add时的顺序和输出时顺序不一样

在代码中发现这个问题。问题是由于:

Map是用来存储key-value类型数据的,一个对在Map的接口定义中被定义为Entry,HashMap内部实现了Entry接口。HashMap内部维护一个Entry数组。 transient Entry[] table;

当put一个新元素的时候,根据key的hash值计算出对应的数组下标。数组的每个元素是一个链表的头指针,用来存储具有相同下标的Entry。

测试代码:

 public class App {
    public static void main(String[] args) {
        mapTest();
    }
    public void listtest() {
        List l = new ArrayList();
        for (int i = 0; i < 10; i++)

        {
            l.add(i);
        }
        System.out.println("List顺序为"+l);
        System.out.println();
        System.out.println("for List顺序如下:");
        for(int j=0;j<l.size();j++)

        {
            System.out.println("j="+j+" l.get("+j+")="+l.get(j));
        }
    }
    public static void mapTest() {
        Map<String,Double> tm = new HashMap();
        tm.put("John Doe", new Double(3434.34));   
        tm.put("Tom Smith", new Double(123.22));   
        tm.put("Jane Baker", new Double(1378.00));   
        tm.put("Todd Hall", new Double(99.22));   
        tm.put("Ralph Smith", new Double(-19.08));
        
        for(Entry<String,Double> en:tm.entrySet()) {
            System.out.println(en.getKey());
        }
    }
}
输出结果:
Todd Hall
John Doe
Ralph Smith
Tom Smith
Jane Baker

解决办法:用LinkedHashMap代替HashMap

参考:http://blog.sina.com.cn/s/blog_60efd9b70102vd5z.html

 

posted @ 2017-11-29 10:38  developer_os  阅读(3723)  评论(0编辑  收藏  举报