HashMap的使用:put、remove和get方法原理

本文详细介绍了HashMap在Android开发中的应用,解析了put、remove和get方法的工作原理。通过理解HashMap的结构,如数组存储链表(或树)节点,深入探讨put方法的putVal实现,涉及哈希碰撞和节点插入规则。同时,概述了remove方法的removeNode过程,以及get方法的查找机制。最后提出了关于HashMap数据结构设计的思考问题。
摘要由CSDN通过智能技术生成

关联项目需求

进行FeatureAB上报的时候,我们使用HashSet的add方法存key值,如果key已存在,则add失败,返回false,如果key不存在,add成功,返回true。

看源码中HashSet的add(E e)方法实现:

HashSet#add

底层还是使用的hashMap的put(E e,Object o)方法。

HashMap的结构:

使用数组的结构存链表(或树)的节点

transient Node<K,V>[] table;
static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }
        ...
    }

hashMap结构:

HashMap的put方法

public V put(K key, V value) {
    return putVal(hash(
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值