遍歷HashMap集合幾種方式

public class bianli {
    //遍歷HashMap集合幾種方式
    public static void main(String[] args) {
        HashMap<Integer,String> map=new HashMap<>();
        map.put(1, "馬太");
        map.put(2, "馬可");
        map.put(3, "路加");
        map.put(4, "約翰");
        //bianlimethod1(map);
        //bianlimethod2(map);
        //bianlimethod3(map);
        bianlimethod4(map);
    }

    public static void bianlimethod1(HashMap<Integer,String> map){
        for (Integer key : map.keySet()) {
            System.out.println(key);
        }
        for (String value : map.values()) {
            System.out.println(value);
        }
    }

    public static void bianlimethod2(HashMap<Integer,String> map){
        Iterator<Map.Entry<Integer,String>> iterator=map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Integer,String> mapEntry=iterator.next();
            System.out.println(mapEntry.getKey()+"==="+mapEntry.getValue());
        }
    }

    public static void bianlimethod3(HashMap<Integer,String> map){
        Set<Integer> keyset=map.keySet();
        for (Integer i : keyset) {
            System.out.println(i+"==="+map.get(i));
        }
    }

    public static void bianlimethod4(HashMap<Integer,String> map){
        map.forEach((key,value)->{
            System.out.println(key+"---"+value);
        });
    }
}

附:
1.面試題:HashMap中hash函數是怎麼實現的?還有哪些hash函數的實現方式?
對於key的hashCode做hash操作,無符號右移16位然後做異或運算。
還有平方取中法,僞隨機數法和取餘數法。這三種效率都比較低。而無符號右移16位異或運算效率是最高的。至於底層是如何計算的我們下面看源碼時給大家講解。

2.面試題:當兩個對象的hashCode相等時會怎麼樣?
會產生哈希碰撞,若key值內容相同則替換舊的value.不然連接到鏈表後面,鏈表長度超過閾值8就轉換爲紅黑樹存儲。

3.面試題:何時發生哈希碰撞和什麼是哈希碰撞,如何解決哈希碰撞?
只要兩個元素的key計算的哈希碼值相同就會發生哈希碰撞。jdk8前使用鏈表解決哈希碰撞。jdk8之後使用鏈表+紅黑樹解決哈希碰撞。

4.面試題:如果兩個鍵的hashcode相同,如何存儲鍵值對?
hashcode相同,通過equals比較內容是否相同。
相同:則新的value覆蓋之前的value
不相同:則將新的鍵值對添加到哈希表中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章