HashMap 之外的 Map 实现
在 Java 生态中,HashMap 无疑是最常用的 Map 实现之一。而 ArrayMap 则是 Android SDK 专为移动端优化的 Map 实现。至于 SparseArray,其底层思路与 ArrayMap 类似,这里一并做个说明。
兼容性提示
需要注意的是,ArrayMap 在旧版支持库中也有兼容实现。若需兼容低版本系统,请留意导入路径的区别:
- 新版:
android.util.ArrayMap - 兼容版:
android.support.v4.util.ArrayMap
HashMap 的内部结构
HashMap 采用'数组 + 链表'的方式存储数据。内部维护一个名为 table 的 Node 类型数组用于存放节点,每个 Node 向后构成单向链表,主要用于处理哈希冲突(即 hash 相同但 key 不同)时的键值对保存。
Node 类的核心结构如下:
static class Node<K,V> implements Entry<K,V> {
final int hash; // key 对象的 hashCode 值
final K key; // key 对象
V value; // value 对象
Node<K,V> next; // 指向下一个节点的引用
}


