JAVA基礎整理(六)---手寫簡單的HashMap來學習hashmap

HashMap學習--手動寫一個簡單的HashMap進行理解

1.結點Node的定義

public class Node {
    public int hash;
    public Object key;
    public Object value;
    public Node next;
}

HashMap的基礎時一個數組,數組裏每一個元素是一個node,他必須包括:hash值,key鍵值,value,next下一個結點,同一個hash值的結點用一條鏈栓起來。node

2.HashMap的定義

Node[] table;//核心數組
    int size;//元素個數
    
     public HashmapTest(){
        table=new Node[16];//初始化數組大小,儘可能2的整數冪
        size=0;
    }

這個數組大小有講究,從兩個極端理解,當大小爲1時,也就是全部的元素栓在一個位子上,也就是退化成了鏈表。若是數組很大,也就是元素全部元素幾乎能夠散在數組的每一個位子上,也就是退化成了數組。至於取2的整數冪,能夠將取餘的操做使用按位&,加快速度,除法在計算機中的速度是很慢的。數組

3.HashMap的增刪改查

增長一個元素

public void put(K key,V value){
        Node newNode=new Node();
        Node lastNode=null;
        Boolean isRepeat=false;
        newNode.hash=myhash(key.hashCode(),table.length);//簡單的計算hash值的函數,就是對數組大小進行取餘,不考慮擴容以及優化
        newNode.key=key;
        newNode.value=value;
        newNode.next=null;
        if(table[newNode.hash]==null){
            table[newNode.hash]=newNode;
        }else{
            Node tmp=table[newNode.hash];
            while (tmp!=null){
                if(tmp.key.equals(key)){
                    isRepeat=true;
                    tmp.value=value;
                    break;
                }else{
                    lastNode=tmp;
                    tmp=tmp.next;
                }

            }
            if(isRepeat==false){
                lastNode.next=newNode;
            }

        }

    }

刪除對應key值的元素

public void delete(K key){
        int hash=myhash(key.hashCode(),table.length);
        Node temp=table[hash];
        Node prevNode=null;//記住前一個結點,刪除時要接上。
        while(temp!=null){
            //第一個結點的特殊操做
            if(temp.key.equals(table[hash].key)){
                //第一個對上了
                if(temp.key.equals(key)){
                     table[hash]=temp.next;
                    break;
                }else{
                    prevNode=temp;
                    temp=temp.next;
                }
            }else{
                if(temp.key.equals(key)){
                    prevNode.next=temp.next;
                    break;
                }else{
                    temp=temp.next;
                }

            }
        }
    }

修改一個元素

public void set(K key,V value){
        Node temp=table[myhash(key.hashCode(),table.length)];
        while (temp!=null){
            if(temp.key.equals(key)){
                temp.value=value;
                break;
            }else {
                temp=temp.next;
            }
        }
    }

查找一個元素

public V get(K key){
        int hash=myhash(key.hashCode(),table.length);
        Node tmp=table[hash];
        if(tmp==null){
            return null;
        }else{
            while (tmp!=null){
                if(tmp.key.equals(key)){
                    return (V)tmp.value;
                }else {
                    tmp=tmp.next;
                }
            }
            return null;
        }
    }
相關文章
相關標籤/搜索