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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM