ArrayList作为数据存储结构的HashMap实现

使用ArrayList实现hashmap

import java.util.ArrayList;

public class HashMap<K, V> {
    private ArrayList<Pair<K, V>>[] buckets;
    private int size;

    public HashMap(int capacity) {
        this.buckets = new ArrayList[capacity];
        this.size = 0;
    }

    public HashMap() {
        this(16);
    }

    public int size() {
        return this.size;
    }

    public boolean isEmpty() {
        return this.size == 0;
    }

    public V get(K key) {
        int index = getIndex(key);
        ArrayList<Pair<K, V>> bucket = buckets[index];
        if (bucket == null) {
            return null;
        }
        for (Pair<K, V> pair : bucket) {
            if (pair.getKey().equals(key)) {
                return pair.getValue();
            }
        }
        return null;
    }

    public void put(K key, V value) {
        int index = getIndex(key);
        if (buckets[index] == null) {
            buckets[index] = new ArrayList<>();
        }
        for (Pair<K, V> pair : buckets[index]) {
            if (pair.getKey().equals(key)) {
                pair.setValue(value);
                return;
            }
        }
        buckets[index].add(new Pair<>(key, value));
        size++;
    }

    public V remove(K key) {
        int index = getIndex(key);
        ArrayList<Pair<K, V>> bucket = buckets[index];
        if (bucket == null) {
            return null;
        }
        for (Pair<K, V> pair : bucket) {
            if (pair.getKey().equals(key)) {
                V value = pair.getValue();
                bucket.remove(pair);
                size--;
                return value;
            }
        }
        return null;
    }

    private int getIndex(K key) {
        int hash = key.hashCode();
        return Math.abs(hash) % buckets.length;
    }

    private static class Pair<K, V> {
        private K key;
        private V value;

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

        public K getKey() {
            return key;
        }

        public void setKey(K key) {
            this.key = key;
        }

        public V getValue() {
            return value;
        }

        public void setValue(V value) {
            this.value = value;
        }
    }
}

加入知识星球:曹操交流(或·直达星球:https://t.zsxq.com/0canxvOCG) ,一起共勉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值