HashMap源码解析,操作系统原理与实践教程第三版答案

本文详细解析了HashMap的源码,包括查询、存储和扩容操作。在查询时,通过键的哈希值找到对应的节点;存储时,根据键值对进行插入,如果键已存在则更新值,否则插入新节点,当链表长度超过一定阈值时,会转换为红黑树;扩容时,新表容量为原容量的两倍,元素位置根据新容量重新计算。
摘要由CSDN通过智能技术生成

*/

public HashMap() {

this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted

}

/**

  • Constructs a new HashMap with the same mappings as the

  • specified Map. The HashMap is created with

  • default load factor (0.75) and an initial capacity sufficient to

  • hold the mappings in the specified Map.

  • @param m the map whose mappings are to be placed in this map

  • @throws NullPointerException if the specified map is null

*/

public HashMap(Map<? extends K, ? extends V> m) {

this.loadFactor = DEFAULT_LOAD_FACTOR;

putMapEntries(m, false);

}

复制代码

查询

/**

  • 返回指定 key 所对应的 value 值,当不存在指定的 key 时,返回 null。

  • 当返回 null 的时候并不表明哈希表中不存在这种关系的映射,有可能对于指定的 key,其对应的值就是 null。

  • 因此可以通过 containsKey 来区分这两种情况。

*/

public V get(Object key) {

Node<K,V> e;

return (e = getNode(hash(key), key)) == null ? null : e.value;

}

/**

  • 1.首先通过 key 的哈希值找到其所在的哈希桶

  • 2.对于 key 所在的哈希桶只有一个元素,此时就是 key 对应的节点,

  • 3.对于 key 所在的哈希桶超过一个节点,此时分两种情况:

  • 如果这是一个 TreeNode,表明通过红黑树存储,在红黑树中查找
    
  • 如果不是一个 TreeNode,表明通过链表存储(链地址法),在链表中查找
    
  • 4.查找不到相应的 key,返回 null

*/

final Node<K,V> getNode(int hash, Object key) {

Node<K,V>[] tab; Node<K,V> first, e; int n; K k;

if ((tab = table) != null && (n = tab.length) > 0 &&

(first = tab[(n - 1) & hash]) != null) {

if (first.hash == hash && // always check first node

((k = first.key) == key || (key != null && key.equals(k))))

return first;

if ((e = first.next) != null) {

if (first instanceof TreeNode)

return ((TreeNode<K,V>)first).getTreeNode(hash, key);

do {

if (e.hash == hash &&

((k = e.key) == key || (key != null && key.equals(k))))

return e;

} while ((e = e.next) != null);

}

}

return null;

}

复制代码

存储

/**

  • 在映射中,将指定的键与指定的值相关联。如
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值