Java8中HashMap的一些新的特性和优化

特性

Java中Map新增的特性主要包括:

default方法:在Java 8中,Map接口新增了一些default方法,如forEach、replace、replaceAll等,可以方便地进行元素遍历和替换操作。

compute方法:在Java 8中,Map接口新增了compute、computeIfAbsent和computeIfPresent等方法,用于根据键对值进行计算、新增或更新操作,可以避免频繁的get和put操作。

merge方法:在Java 8中,Map接口新增了merge方法,用于合并相同键的值。当具有相同键的值存在时,可以通过提供一个合并函数来决定如何合并这些值。

forEach方法:在Java 8中,Map接口新增了forEach方法,可以通过Lambda表达式对Map的所有键值对进行遍历操作,简化了代码。

getOrDefault方法:在Java 8中,Map接口新增了getOrDefault方法,可以获取指定键对应的值,如果键不存在,则返回指定的默认值。

除此之外,自Java 9开始,Map接口还新增了一些其他的方法,如of、ofEntries等,用于创建和操作不可变的Map对象。

Map插入数据说明

这是HashMap的put方法中的putVal部分,用于插入一个(key, value)映射。该方法首先检查哈希表是否为空或长度为0,如果是则执行resize方法扩容;然后根据哈希值计算出对应的数组下标i,并在该位置上搜索是否有相同键值的节点。如果有,则更新该节点的value值;如果没有,则插入新节点。

如果插入的节点数超出了扩容阈值,会执行resize方法进行扩容。如果插入的节点是树节点,则调用putTreeVal方法进行插入操作,否则在链表中顺序查找合适的位置进行插入。

最后会自增哈希表的修改次数modCount、结点数量size,并在插入后执行afterNodeInsertion方法,返回插入的value值。如果插入的键值已经存在,且onlyIfAbsent参数为false,则会更新该键对应的value值,否则不更新,返回原来的value值。如果节点已存在,则调用afterNodeAccess方法。

Map插入数据的优化

Java中的HashMap对于节点插入的索引特性进行了优化,主要在以下几个方面:

哈希值高效计算:HashMap使用key的hashCode()方法计算哈希值,通过与数组长度-1进行按位与运算来得到数组下标。这样可以避免对数组长度取余导致的性能损失。

红黑树的应用:当链表中的元素超过一定数量阈值(默认为8)时,会将链表转换为红黑树。红黑树可以提高搜索、插入和删除等操作的效率,减少时间复杂度。

链表和红黑树的自动转换:在插入节点时,会判断当前桶中的节点数量。如果链表长度超过阈值,则将链表转换为红黑树;如果红黑树节点数减少到小于阈值,则将红黑树转换回链表。这样可以在保证性能的同时,节省内存空间。

增量扩容:在HashMap的容量达到一定的填充因子(默认为0.75)时,会进行扩容。为了避免一次性扩容导致的性能损失,HashMap采用增量扩容的方式,在扩容时增加了一个阈值,每次插入节点时判断是否需要扩容,如果需要,则只扩容一部分,而不是整个哈希表。

通过以上优化,HashMap在插入节点时能够高效地定位到对应的索引位置,并选择合适的数据结构(链表或红黑树)进行节点的插入,提高了插入操作的效率和性能。

Simply put

Features

The new features in Java’s Map mainly include:

Default methods: In Java 8, the Map interface added some default methods, such as forEach, replace, replaceAll, etc., which can conveniently traverse and replace elements.

Compute methods: In Java 8, the Map interface added methods like compute, computeIfAbsent, and computeIfPresent for calculating, adding, or updating values based on keys, avoiding frequent get and put operations.

Merge method: In Java 8, the Map interface added the merge method, used to merge values with the same key. When values with the same key exist, a merge function can be provided to decide how to merge these values.

ForEach method: In Java 8, the Map interface added the forEach method, which can traverse all key-value pairs in the Map using a Lambda expression, simplifying the code.

GetOrDefault method: In Java 8, the Map interface added the getOrDefault method, which can get the value corresponding to the specified key. If the key does not exist, it returns the specified default value.

In addition, starting from Java 9, the Map interface added some other methods, such as of, ofEntries, etc., for creating and operating immutable Map objects.

Explanation of Map Inserting Data

This is the putVal part in HashMap’s put method, used to insert a (key, value) mapping. The method first checks whether the hash table is empty or of length 0, if so, it executes the resize method to expand; then it calculates the corresponding array subscript i based on the hash value, and searches for a node with the same key value at this position. If there is, it updates the value of the node; if not, it inserts a new node.

If the number of nodes inserted exceeds the expansion threshold, the resize method is executed to expand. If the inserted node is a tree node, the putTreeVal method is called for insertion, otherwise, it is inserted in the appropriate position in the list in order.

Finally, it will increment the modification times modCount, node quantity size of the hash table, and execute the afterNodeInsertion method after insertion, returning the inserted value. If the inserted key value already exists, and the onlyIfAbsent parameter is false, it will update the value corresponding to this key, otherwise, it will not update and return the original value. If the node already exists, the afterNodeAccess method is called.

Optimization of Map Inserting Data

Java’s HashMap has optimized the index feature for node insertion, mainly in the following aspects:

Efficient hash value calculation: HashMap uses the hashCode() method of the key to calculate the hash value, and obtains the array subscript by bitwise AND operation with the array length-1. This can avoid the performance loss caused by taking the remainder of the array length.

Application of Red-Black Tree: When the number of elements in the list exceeds a certain threshold value (default is 8), the list will be converted into a red-black tree. The red-black tree can improve the efficiency of operations such as search, insertion, and deletion, and reduce time complexity.

Automatic conversion of linked list and red-black tree: When inserting nodes, it will judge the number of nodes in the current bucket. If the length of the list exceeds the threshold, the list will be converted to a red-black tree; if the number of red-black tree nodes decreases to less than the threshold, the red-black tree will be converted back to the list. This can ensure performance while saving memory space.

Incremental expansion: When the capacity of HashMap reaches a certain fill factor (default is 0.75), it will be expanded. To avoid the performance loss caused by one-time expansion, HashMap uses incremental expansion. When expanding, it adds a threshold. Each time a node is inserted, it checks whether expansion is needed. If so, only a part of it is expanded, not the entire hash table.

Through the above optimization, HashMap can efficiently locate the corresponding index position when inserting nodes and choose the appropriate data structure (linked list or red-black tree) for node insertion, improving the efficiency and performance of the insertion operation.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

P("Struggler") ?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值