HashMap、ArrayMap、SparseArray分析比较

一、原理分析
1、HashMap分析
HashMap是基于hash表非同步map实现,key和value都可以为null。其hash表实现方式是”拉链法”,可理解为链表的数组,如下图所示:
这里写图片描述
HashMap部分源码如下:

/**
 * The hash table. If this hash map contains a mapping    for null, it is
 * not represented this hash table.
 */
 transient HashMapEntry<K, V>[] table;
/**
 * Maps the specified key to the specified value.
 *
 * @param key
 *            the key.
 * @param value
 *            the value.
 * @return the value of any previous mapping with the specified key or
 *         {@code null} if there was no such mapping.
 */
@Override public V put(K key, V value) {
    if (key == null) {
        return putValueForNullKey(value);
    }

    int hash = Collections.secondaryHash(key);
    HashMapEntry<K, V>[] tab = table;
    int index = hash & (tab.length - 1);
    for (HashMapEntry<K, V> e = tab[index]; e != null; e = e.next) {
        if (e.hash == hash && key.equals(e.key)) {
            preModify(e);
            V oldValue = e.value;
            e.value = value;
            return oldValue;
        }
    }

    // No entry for (non-null) key is present; create one
    modCount++;
    if (size++ > threshold) {
        tab = doubleCapacity();
        index = hash & (tab.length - 1);
    }
    addNewEntry(key, value, hash, index);
    return null;
}

/**
 * Returns the value of the mapping with the specified key.
 *
 * @param key
 *            the key.
 * @return the value of the mapping with the specified key, or {@code null}
 *         if no mapping for the specified key is found.
 */
public V get(Object key) {
    if (key == null) {
        HashMapEntry<K, V> e = entryForNullKey;
        return e == null ? null : e.value;
    }

    int hash = Collections.secondaryHash(key);
    HashMapEntry<K, V>[] tab = table;
    for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];
         e != null; e = e.next) {
        K eKey = e.key;
        if (eKey == key || (e.hash == hash && key.equals(eKey))) {
            return e.value;
        }
    }
    return null;
}

/**
 * Creates a new entry for the given key, value, hash, and index and
 * inserts it into the hash table. This method is called by put
 * (and indirectly, putAll), and overridden by LinkedHashMap. The hash
 * must incorporate the secondary hash function.
 */
void addNewEntry(K key, V value, int hash, int index) {
    table[index] = new HashMapEntry<K, V>(key, value, hash, table[index]);
}
static class HashMapEntry<K, V> implements Map.Entry<K, V> {
   
    final K key;
    V value;
    final int hash;
    HashMapEntry<K, V> next;

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

HashMap的HashMapEntry

/**
 * Doubles the capacity of the hash table. Existing entries are placed in
 * the correct bucket on the enlarged table. If the current capacity is,
 * MAXIMUM_CAPACITY, this method is a no-op. Returns th
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
HashMap是Java中常用的一种数据结构,它基于哈希表实现。下面是HashMap的简要源码分析: 1. 数据结构:HashMap内部使用了数组和链表(或红黑树)来实现。数组的每个位置称为桶(bucket),每个桶存储一个链表的头节点。当链表长度超过阈值(默认为8)时,链表会转换为红黑树,提高查找效率。 2. 成员变量: - `transient Node<K,V>[] table`:用于存储元素的数组,是HashMap的主要数据结构。初始时为null,第一次插入元素时才会初始化。 - `transient int size`:HashMap中元素的个数。 - `int threshold`:扩容的阈值,当元素个数超过此值时触发扩容操作。 - `float loadFactor`:负载因子,用于计算扩容阈值,默认值为0.75。 - `int modCount`:用于记录HashMap结构修改的次数,用于迭代器的快速失败机制。 - `static final int DEFAULT_INITIAL_CAPACITY`:默认初始容量为16。 - `static final int MAXIMUM_CAPACITY`:最大容量,为2^30。 - `static final float DEFAULT_LOAD_FACTOR`:默认负载因子。 - `static final int TREEIFY_THRESHOLD`:链表转化为红黑树的阈值。 - `static final int UNTREEIFY_THRESHOLD`:红黑树转化为链表的阈值。 - `static final int MIN_TREEIFY_CAPACITY`:最小树化容量。 3. 常用方法: - `put(K key, V value)`:向HashMap中插入键值对,如果键已存在,则更新值,否则新增键值对。 - `get(Object key)`:根据键获取对应的值。 - `remove(Object key)`:根据键移除对应的键值对。 - `containsKey(Object key)`:判断是否包含指定的键。 - `containsValue(Object value)`:判断是否包含指定的值。 - `size()`:返回HashMap中键值对的个数。 - `isEmpty()`:判断HashMap是否为空。 - `clear()`:清空HashMap中的所有键值对。 4. 实现原理: - 添加元素时,根据键的hashCode()计算数组下标,如果该位置为空,则直接插入;如果该位置已经有元素,则通过equals()方法比较键的相等性。如果发生冲突(hashCode相等但不相等),则将元素插入链表或红黑树中。 - 查找元素时,根据键的hashCode()计算数组下标,然后遍历链表或红黑树,通过equals()方法比较键的相等性,找到对应的值。 - 扩容时,创建新的两倍大小的数组,将旧数组中的元素重新散列到新数组中。 以上是HashMap的简要源码分析HashMap是Java集合框架中常用的数据结构之一,具有高效的插入、查找和删除操作,适用于存储键值对的场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值