亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java Javagetting Started What is the expansion mechanism of hashmap?

What is the expansion mechanism of hashmap?

Mar 15, 2023 pm 03:39 PM
java hashmap

The expansion mechanism of hashmap is: recalculate the capacity and replace the original array with a new array. Recalculate all the data of the original array and insert a new array, and then point to the new array; if the array has reached the maximum value before capacity expansion, directly set the threshold to the maximum integer and return it.

What is the expansion mechanism of hashmap?

#The operating environment of this tutorial: windows7 system, java8, Dell G3 computer.

What is resize?

?Capacity expansion (resize): It is to recalculate the capacity and continuously add elements to the HashMap object. When the array inside the HashMap object cannot load more elements, the object needs to be expanded. The length of the array so that more elements can be accommodated. Of course, arrays in Java cannot be automatically expanded. The method is to use a new array to replace the existing array with a small capacity. Just like we use a small bucket to hold water, if we want to hold more water, we have to change to a larger bucket. .

When will the capacity be expanded?

When adding elements to a container, the number of elements in the current container will be judged. If it is greater than or equal to the threshold (threshold), that is, the number of elements in the current container is greater than the length of the current array. When multiplied by the value of the loading factor, it will automatically expand.

Hashmap expansion principle

HashMap expansion is to recalculate the capacity and continuously add elements to hashMap. When hashMap cannot load new elements, The object will need to expand the array capacity to accommodate more elements.

What is the expansion mechanism of hashmap?

HashMap capacity expansion characteristics, the greater the loading factor, the higher the space utilization, the more elements need to be filled before expansion, the faster the put operation, but the linked list is easy to pass Long, hash collision probability is high, and get operation is slow. The smaller the loading factor, the faster the get operation, the shorter the linked list, and the lower the probability of hash collision. However, space utilization is low. Too many put elements will lead to frequent expansion and affect performance.

What is the expansion mechanism of hashmap?

The capacity expansion principle of HashMap: The Hashmap method is to replace the original array with a new array, recalculate all the data in the original array, insert the new array, and then point to the new array; If the array has reached the maximum before expansion, the threshold is directly set to the maximum integer and returned.

The expansion process

The following uses source code, pictures, and text descriptions to introduce the expansion process of HashMap.

/** 
 * HashMap 添加節(jié)點 
 * 
 * @param hash        當(dāng)前key生成的hashcode 
 * @param key         要添加到 HashMap 的key 
 * @param value       要添加到 HashMap 的value 
 * @param bucketIndex 桶,也就是這個要添加 HashMap 里的這個數(shù)據(jù)對應(yīng)到數(shù)組的位置下標(biāo) 
 */  
void addEntry(int hash, K key, V value, int bucketIndex) {  
    //數(shù)組擴容條件:1.已經(jīng)存在的key-value mappings的個數(shù)大于等于閾值  
    //             2.底層數(shù)組的bucketIndex坐標(biāo)處不等于null  
    if ((size >= threshold) && (null != table[bucketIndex])) {  
        resize(2 * table.length);//擴容之后,數(shù)組長度變了  
        hash = (null != key) ? hash(key) : 0;//為什么要再次計算一下hash值呢?  
        bucketIndex = indexFor(hash, table.length);//擴容之后,數(shù)組長度變了,在數(shù)組的下標(biāo)跟數(shù)組長度有關(guān),得重算。  
    }  
    createEntry(hash, key, value, bucketIndex);  
}  
  
/** 
 * 這地方就是鏈表出現(xiàn)的地方,有2種情況 
 * 1,原來的桶bucketIndex處是沒值的,那么就不會有鏈表出來啦 
 * 2,原來這地方有值,那么根據(jù)Entry的構(gòu)造函數(shù),把新傳進來的key-value mapping放在數(shù)組上,原來的就掛在這個新來的next屬性上了 
 */  
void createEntry(int hash, K key, V value, int bucketIndex) {  
    HashMap.Entry<K, V> e = table[bucketIndex];  
    table[bucketIndex] = new HashMap.Entry<>(hash, key, value, e);  
    size++;  
}

In the above addEntry method, if size (number of elements in the current container) is greater than or equal to threshold (array length multiplied by load factor), and the bucketIndex coordinate of the underlying array is not equal to null, then it will be executed Expansion (resize) . Otherwise, the expansion will not occur.

The following will focus on the expansion process:

        void resize(int newCapacity) {   //傳入新的容量
            Entry[] oldTable = table;    //引用擴容前的Entry數(shù)組
            int oldCapacity = oldTable.length;
            if (oldCapacity == MAXIMUM_CAPACITY) {  //擴容前的數(shù)組大小如果已經(jīng)達到最大(2^30)了
                threshold = Integer.MAX_VALUE; //修改閾值為int的最大值(2^31-1),這樣以后就不會擴容了
                return;
            }
     
            Entry[] newTable = new Entry[newCapacity];  //初始化一個新的Entry數(shù)組
            transfer(newTable);	此行有遺漏,勘誤見下面引用	//!!將數(shù)據(jù)轉(zhuǎn)移到新的Entry數(shù)組里
            table = newTable;                           //HashMap的table屬性引用新的Entry數(shù)組
            threshold = (int) (newCapacity * loadFactor);此行有遺漏,勘誤見下面引用//修改閾值
        }

Corrected by wenni328 blogger: transfer(newTable); ==> transfer(newTable, initHashSeedAsNeeded(newCapacity));
threshold = (int) (newCapacity * loadFactor); ==> threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY 1);

Before expansion, first obtain the reference address of the array before expansion and store it in the oldTable variable, and then determine whether the length of the array before expansion reaches int The maximum value stored in the type. If so, the expansion will be given up because the array capacity has reached the maximum and cannot be expanded.

The picture below shows the state after the program executes the Entry[] newTable = new Entry[newCapacity]; code:

## ?

What is the expansion mechanism of hashmap?

Here is the use of a larger capacity An array is used to replace the existing array with a small capacity. The transfer() method copies the elements of the original Entry array to the new Entry array.

        void transfer(Entry[] newTable) {
            Entry[] src = table;                   //src引用了舊的Entry數(shù)組
            int newCapacity = newTable.length;
            for (int j = 0; j < src.length; j++) { //遍歷舊的Entry數(shù)組
                Entry<K, V> e = src[j];             //取得舊Entry數(shù)組的每個元素
                if (e != null) {
                    src[j] = null;//釋放舊Entry數(shù)組的對象引用(for循環(huán)后,舊的Entry數(shù)組不再引用任何對象)
                    do {
                        Entry<K, V> next = e.next;
                        int i = indexFor(e.hash, newCapacity); //??!重新計算每個元素在數(shù)組中的位置
                        e.next = newTable[i]; //標(biāo)記[1]
                        newTable[i] = e;      //將元素放在數(shù)組上
                        e = next;             //訪問下一個Entry鏈上的元素
                    } while (e != null);
                }
            }
        }

        static int indexFor(int h, int length) {
            return h & (length - 1);
        }
The reference of newTable[i] is assigned to e.next, that is,

uses the head insertion method of a singly linked list, and new elements at the same position will always be placed at the head of the linked list. position; in this way, elements placed on an index first will eventually be placed at the end of the Entry chain (if a hash conflict occurs). Elements in the same Entry chain in the old array may be placed in different positions in the new array after recalculating the index position.

The transfer process will be demonstrated in the form of pictures below (the red fonts in the pictures below indicate the differences from the above pictures, the following pictures are like this, and the descriptions in red fonts will not be repeated)

The picture below shows the state after the program executes the src[j] = null; code (this is the state during the first loop):


What is the expansion mechanism of hashmap?

First, assign the reference address of the table[] array to the src[] array.

Then, Entry e = src[j]; is to transfer the linked list at the src[j] position to the e variable for storage. Since the linked list at src[j] has been given to e for storage, you can boldly set src[j]=null; and then wait for garbage collection.

The picture below shows the state after the program executes the Entry next = e.next; code (this is the state during the first loop):

What is the expansion mechanism of hashmap?

The value of e.next is first backed up to the next variable. Subsequent code will change the pointer of e.next, so the value of e.next is backed up here.

The picture below shows the state after the program executes the e.next = newTable[i]; code (this is the state during the first loop):
#?

What is the expansion mechanism of hashmap?

## Since the value of newTable[3] is null, e.next is null, as shown in the figure above.

The picture below shows the state after the program executes the newTable[i] = e; code (this is the state during the first loop):


?

What is the expansion mechanism of hashmap?## The following picture shows the state after the program executes the e = next; code (this is the state during the first loop):

What is the expansion mechanism of hashmap? As shown above, Entry1 This node is successfully inserted into newTable. At the end of the cycle, because e!=null is judged, the above process will be repeated until all nodes are moved to newTable.

Summary

Expansion is a particularly performance-intensive operation, so when programmers use HashMap, they estimate the size of the map and provide it during initialization. A rough value to avoid frequent map expansion.
  • The load factor can be modified, or it can be greater than 1, but it is recommended not to modify it easily unless the situation is very special.
  • HashMap is thread-unsafe. Do not operate HashMap at the same time in a concurrent environment. It is recommended to use ConcurrentHashMap.
  • JDK1.8 introduces red-black trees to greatly optimize the performance of HashMap.
  • For more programming-related knowledge, please visit:
Programming Teaching

! !

The above is the detailed content of What is the expansion mechanism of hashmap?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Google Chrome cannot open local files Google Chrome cannot open local files Aug 01, 2025 am 05:24 AM

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

See all articles