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

news/2024/11/24 6:59:11/

特性

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.


http://www.ppmy.cn/news/740612.html

相关文章

VBS遍历文件

一下这段代码是我自己无聊是写的,希望对有用得上的人有帮助。 用处嘛,见标题。 dim fso 这一行可以不写set fso createObject("scripting.fileSystemObject")sub traverse(address)set folder fso.getFolder(address)Set folds folder.su…

vbs操作文件!!

创建文本文件 Set objFSO CreateObject("Scripting.FileSystemObject")Set objFile objFSO.CreateTextFile("C:/FSO/ScriptLog.txt") 检察文件是否存在 Set objFSO CreateObject("Scripting.FileSystemObject")If objFSO.FileExists("…

.VBS后缀文件

PHP交流群:294088839 Python交流群:652376983 vbs VBS是基于Visual Basic的脚本语言。VBS的全称是:Microsoft Visual Basic Script Editon。(微软公司可视化BASIC脚本版)。 恶作剧代码 on error resume next dim WSHshellA set WSHshell…

vbs 删除文件.

Dim oFSO,a,b,fs SET bWSCRIPT.CreateObject("WSCRIPT.SHELL") b.POPUP("确定要删除C盘1.txt文件?") On Error Resume Next Set oFSO CreateObject("Scripting.FileSystemObject") Set …

vbs复制自身到启动文件夹

dim fso set fsoCreateObject("scripting.FileSystemObject") set Wsh WScript.CreateObject("WScript.Shell") pathname Wsh.SpecialFolders("startup")"\" 获取启动文件夹 fso.GetFile(WScript.ScriptFullName).Copy(pathname&am…

VBS的加密跟解密

VBS加密: 复制以下代码,用记事本另存为,“VBS加密” 保存。 set fsocreateobject("scripting.filesystemobject") scfinputbox("请输入要加密的脚本文件名","VBS加密程序","*.vbs") set opfso.opentextfile(sc…

VBS下载文件

把以下代码存成.VBS&#xff0c;然后在命令行里调用。参数为&#xff1a;网址 本地文件 dim url dim file Set objArgs WScript.Arguments if objArgs.Count < 2 then msgbox("Invalid param count! should be: url pathfilename") Else url objAr…

整人的vbs文件

桌面创建一个text文件 msgbox("你是sb么")xmsgbox("你是sb么",VbOkCancel) if xVbOk then msgbox("你很机智") elseif xVbCancel then msgbox("再见") set ws createobject("wscript.shell") ws.run"cmd.exe /c …