HashMap、ArrayMap、SparseArray分析比较

本文对比分析了HashMap、ArrayMap和SparseArray三种数据结构。HashMap使用拉链法实现,支持key和value为null,扩容时新建两倍大小的table。ArrayMap采用int[]保存hashCode,Object[]保存键值对,通过二分法查找,删除或添加数据时会进行空间调整,适用于小数据量场景。SparseArray则主要针对整数key,适合Android环境。在选择时需考虑数据量、性能和空间效率等因素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、原理分析
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 meth
### ArrayMapSparseArray 的使用场景与性能比较 #### 1. **基本概念** ArrayMap 是一种内存优化版本的 HashMap,适用于键值对数量较少的情况。它的设计目标是在小规模数据集上提供更高的效率和更低的内存占用[^3]。 SparseArray 则是一种专门为 `int` 类型键设计的数据结构。它通过两个数组分别存储键和值,避免了 Java 中自动装箱带来的开销。因此,对于整数类型的键,SparseArray 提供了更好的性能和更低的内存消耗[^2]。 --- #### 2. **内部实现机制** - **ArrayMap 实现** ArrayMap 内部维护了一个对象数组用于存储键值对,并采用了类似于红黑树的方式进行排序和查找操作。这使得其在插入、删除和查询时的时间复杂度接近 O(log n)[^3]。 - **SparseArray 实现** SparseArray 使用两个独立的数组分别保存键 (`mKeys`) 和值 (`mValues`)。由于键固定为 `int` 类型,它可以利用二分查找算法快速定位指定键的位置,时间复杂度同样为 O(log n)。此外,SparseArray 还支持标记已删除项的功能以减少不必要的移动操作[^2]。 --- #### 3. **性能对比** | 特性 | ArrayMap | SparseArray | |---------------------|-----------------------------------|----------------------------------| | 键类型 | 支持任意可哈希的对象 | 仅限于 `int` | | 插入/删除/查询速度 | 接近 O(log n),适合通用场景 | 同样为 O(log n),针对 `int` 更高效 | | 内存占用 | 较低 | 极低 | | 扩展能力 | 动态扩展 | 固定大小,默认容量较小 | 从以上表格可以看出,在处理少量数据或者特定类型(如 `int`)的情况下,SparseArray 明显优于其他集合类;而对于更加灵活的需求,则可以选择 ArrayMap 或者传统 HashMap 来满足应用需求[^4]。 --- #### 4. **适用场景分析** - **ArrayMap 场景** 当应用程序需要频繁地增删改查操作且涉及多种不同类型的键时,推荐优先考虑使用 ArrayMap。例如 UI 控件绑定事件处理器映射表等场合都可以很好地发挥其优势。 - **SparseArray 场景** 如果业务逻辑中存在大量的基于索引访问资源文件 ID 或者视图组件引用编号的操作,则应毫不犹豫选用 SparseArray 替代传统的 Map 结构来提升整体运行效率并节省宝贵硬件资源[^2]。 --- ```java // 示例代码:如何正确选择合适的容器类型? public void exampleUsage() { // 使用 ArrayMap 存储字符串作为 Key 的情况 ArrayMap<String, String> arrayMapExample = new ArrayMap<>(); arrayMapExample.put("name", "John"); // 使用 SparseArray 处理 Int 型 Keys 的情形 SparseArray<String> sparseArrayExample = new SparseArray<>(); sparseArrayExample.put(100, "ValueForIntKey"); System.out.println(arrayMapExample.get("name")); // 输出 John System.out.println(sparseArrayExample.get(100)); // 输出 ValueForIntKey } ``` ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值