1. 程式人生 > >理解HashMap底層原理,一個簡單的HashMap例子

理解HashMap底層原理,一個簡單的HashMap例子

amp builder out print node get bject sta value

package com.jl.testmap;

/**
 *  自定義一個HashMap
 * @author JiangLai
 *
 */
public class MyHashMap<K,V> {

    Node<K,V>[] table;//位桶數組
    int size;//存放鍵值對的個數
    
    public MyHashMap() {
        table = new Node[16];//長度一般定義為2的整數次冪
    }
     
    public void put(K key,V value) {
        
        
//定義新的節點對象 Node newNode = new Node(); newNode.hash = myHash(key.hashCode(), table.length); newNode.key = key; newNode.value = value; newNode.next = null; Node temp = table[newNode.hash]; Node itorLast = null;//正在遍歷的最後一個元素
if(temp==null) { //此處數組元素為空,則直接將新節點放入 table[newNode.hash] = newNode; size++; }else { //此處數組元素 不為空,則遍歷整個鏈表 while (temp!=null) { //判斷key是否重復,相同則替換, if(temp.key.equals(key)) { temp.value
= value;//只是覆蓋value即可,其他的值不變。(hash,key,next) break; }else {//如果不重復,則遍歷下一個 itorLast = temp; temp = temp.next; } } if(itorLast!=null) { itorLast.next = newNode; size++; } } } public V get(K key) { int hash = myHash(key.hashCode(), table.length); Object value = null; if(table[hash] != null) { Node<K,V> temp = table[hash]; while (temp!=null) { if(temp.key.equals(key)) {//如果相等,則返回對應的值 value = temp.value; break; }else { temp = temp.next; } } } return (V)value; } //計算Hash值 public int myHash(int v,int length) { //二者作用一樣 // System.out.println(v&(length-1));//直接位運算,效率高. // System.out.println(v%(length-1));//取余運算,效率低. return v&(length-1); } @Override public String toString() { //{10:aa,20:bb} StringBuilder sb = new StringBuilder("{"); //遍歷數組 for(int i=0;i<table.length;i++) { Node<K,V> temp = table[i];//當前元素 //遍歷鏈表 while (temp!=null) { //當前元素的key和value sb.append(temp.key+":"+temp.value+","); //當前元素的下一個元素 temp = temp.next; } } sb.setCharAt(sb.length()-1, ‘}‘); return sb.toString(); } public static void main(String[] args) { MyHashMap<Integer,String> map01 = new MyHashMap<>(); map01.put(10, "001"); map01.put(20, "002"); System.out.println(map01); System.out.println(map01.get(10)); } }
package com.jl.testmap;

/**
 * 用於TestHashMap中
 * @author JinagLai
 */
public class Node<K,V> {
    
     int hash;//HashCode
     K key;//
     V value;//
     Node<K,V> next;//下一個節點
    
    
    
}

理解HashMap底層原理,一個簡單的HashMap例子