hashmap 简单实现

import java.util.LinkedList;

public class MyHashMap<K,V> {
    private int capacity;
    private float loadFactor;
    private LinkedList<Node>[] array;
    private int size;

    public MyHashMap(int capacity, float loadFactor) {
        this.capacity = capacity;
        this.loadFactor = loadFactor;
        array = new LinkedList[capacity];
        size = 0;
    }

    public V get(K key) {
        int index = key.hashCode() % capacity;
        LinkedList<Node> list = array[index];
        if (list != null) {
            for (Node node : list) {
                if (node.key.equals(key)) {
                    return node.value;
                }
            }
        }
        return null;
    }

    public void put(K key, V value) {
        int index = key.hashCode() % capacity;
        LinkedList<Node> list = array[index];
        if (list == null) {
            list = new LinkedList<Node>();
            array[index] = list;
        }
        for (Node node : list) {
            if (node.key.equals(key)) {
                node.value = value;
                return;
            }
        }
        list.add(new Node(key, value));
        size++;
        if (size / (float)capacity > loadFactor) {
            resize();
        }
    }

    private void resize() {
        capacity = capacity * 2;
        LinkedList<Node>[] newArray = new LinkedList[capacity];
        for (LinkedList<Node> list : array) {
            if (list != null) {
                for (Node node : list) {
                    int index = node.key.hashCode() % capacity;
                    LinkedList<Node> newList = newArray[index];
                    if (newList == null) {
                        newList = new LinkedList<Node>();
                        newArray[index] = newList;
                    }
                    newList.add(node);
                }
            }
        }
        array = newArray;
    }

    private class Node {
        K key;
        V value;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值