手写一个简单的HashMap

过去的,未来的
2020-03-18 / 0 评论 / 0 点赞 / 704 阅读 / 0 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2020-03-19,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
public class MyHashMap<K,V> {
    private static final int DEFAULT_CAPTIY=16;
    private static final float DEFAULT_FACOTR=0.75f;
    private float loadFactor = 0;
    private int initCapacity = 0;
    private Node[] table=null;
    public MyHashMap(){
        this.loadFactor=DEFAULT_FACOTR;
        this.initCapacity=DEFAULT_CAPTIY;
        table=new Node[this.initCapacity];
    }
    public MyHashMap(int initCapacity, float loadFactor){
        this.loadFactor = loadFactor;
        this.initCapacity = initCapacity;
        table = new Node[this.initCapacity];
    }
    private int hash(K key){
        int h;
        return (key == null) ? 0 : Math.abs((h = key.hashCode())) ^ (h >>> 16);
    }
    public V put(K key, V value) {
        // 确定index
        int index = hash(key) % initCapacity;
        if (table[index] != null) {
            Node<K, V> e = table[index];
            Node<K, V> e2 = null;
            while (e != null) {
                if (hash(e.key) == hash(key) && e.key.equals(key)) {
                    // 如果键相同,则更新值
                    e.value = value;
                }
                // 遍历链表判断是否已经存在相同的key
                e2 = e;
                e = e.next;
            }
            // 如果不存在相同的key,则直接插到尾结点的后面
            e2.next = new Node<>(key, value, null, index);
        } else {
            // 如果table[index]处为空,则直接插入
            Node<K, V> e = new Node<>(key, value, null, index);
            table[index] = e;
        }
        return value;
    }
    public V get(K k){
        int keyHash=hash(k)%initCapacity;
        Node<K,V> e=table[keyHash];
        if(e==null)
            return null;
        while (e!=null){
            if(hash(e.key) == hash(k) && e.key.equals(k))
                return V;
            e=e.next;
        }
        return null;
    }
}
class Node<K,V> {
    public int hash;
    public K key;
    public V value;
    public Node next;
    public Node(K k,V v,Node next, int hash){
        this.key=k;
        this.value=v;
        this.next=next;
        this.hash=hash;
    }
}

0

评论区