自己动手实现HashMap

实现了HashMap的增删改查方法,直接上代码。。。

public class YmhHashMap {
    private YmhLinkedList[] list = new YmhLinkedList[999];
    private int size;

    //增
    public void put(Object key, Object value) {
        int pos = key.hashCode() % 999;
        pos = pos > 0 ? pos : -pos;
        YmhLinkedList ymhLinkedList = null;
        Bean bean = new Bean(key, value);

        if (list[pos] == null) {
            ymhLinkedList = new YmhLinkedList();
        } else {
            ymhLinkedList = list[pos];
            for (int i = 0; i < ymhLinkedList.size; i++) {
                if (((Bean) ymhLinkedList.get(i)).key.equals(key)) {
                    ((Bean) ymhLinkedList.get(i)).value = value;
                    return;
                }
            }
        }
        size++;
        ymhLinkedList.add(bean);
    }

    //删
    public Object remove(Object key) {
        int pos = key.hashCode() % 999;
        pos = pos > 0 ? pos : -pos;
        YmhLinkedList ymhLinkedList = null;
        ymhLinkedList = list[pos];
        if (ymhLinkedList == null) {
            return null;
        }
        for (int i = 0; i < ymhLinkedList.size; i++) {
            if (((Bean) ymhLinkedList.get(i)).key.equals(key)) {
                Object oldValue = ((Bean) ymhLinkedList.get(i)).value;
                ymhLinkedList.remove(i);
                size--;
                return oldValue;
            }
        }
        return null;
    }

    //改
    public Object set(Object key, Object value) {
        int pos = key.hashCode() % 999;
        pos = pos > 0 ? pos : -pos;
        YmhLinkedList ymhLinkedList = null;
        ymhLinkedList = list[pos];
        if (ymhLinkedList == null) {
            return null;
        }
        for (int i = 0; i < ymhLinkedList.size; i++) {
            if (((Bean) ymhLinkedList.get(i)).key.equals(key)) {
                Object oldValue = ((Bean) ymhLinkedList.get(i)).value;
                ((Bean) ymhLinkedList.get(i)).value = value;
                return oldValue;
            }
        }
        return null;
    }

    // 查
    public Object get(Object key) {
        int pos = key.hashCode() % 999;
        pos = pos > 0 ? pos : -pos;
        YmhLinkedList ymhLinkedList = null;
        ymhLinkedList = list[pos];
        if (ymhLinkedList == null) {
            return null;
        }
        for (int i = 0; i < ymhLinkedList.size; i++) {
            if (((Bean) ymhLinkedList.get(i)).key.equals(key)) {
                return ((Bean) ymhLinkedList.get(i)).value;
            }
        }
        return null;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值