Principles and Application of HashMap in Java

Source: Internet
Author: User

HashMap inHashTableThere are basically three improvements on: * The Map interface is installed, rather than the Dictionary of JDK. The Map interface is richer and more reasonable. * The null key and null value are acceptable. * The synchronization speed is greatly improved (ConcurrentHashMap is used for synchronization, with several improvements: Segment locks, immutability, Unsafe CAS operations, and weak consistent iterators ).

        if (key == null)            return putForNullKey(value);

The principle of hash ing used, since it is hash, it is inevitable to haveConflict, HashMap uses the linked list method to resolve conflicts. When a conflict occurs, the new element points to the header node, and the new element is placed in the array. LRU is the Least Recently Used algorithm of Least Recently Used. The fourth parameter of Entry is the pointing element.

        Entry
 
   e = table[bucketIndex];        table[bucketIndex] = new Entry<>(hash, key, value, e);
 

For expansionResizingWhen is the scale-up time doubled? The performance of the hash algorithm decreases sharply when it approaches the bucket. Therefore, you must expand the capacity when there is a gap between the upper limit and the upper limit of the bucket. This is loadfactor.Load Factor. By default, the HashMap bucket is limited to 16 and the load is 0.75. That is, 12 instances are installed. Capacity bucket limit, loadFactor load, and threshold.

        this.loadFactor = loadFactor;        threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);        table = new Entry[capacity];

Like other collection classes, you can initialize the size during initialization to avoid subsequent resizing. HashMap is set to be the first parameter to be greater than the parameter value when setting the hour2 exponential power. Why? It must be related to performance. Because hashCode is an int number, it should be limited to the maximum size of the bucket. When the range is limited, the use of 'and' will be more efficient, that is, hashCode & (length-1 ). If the length is 16, 16-1 = 15. So it is compared with the upper 1111.

// At initialization // Find a power of 2> = initialCapacity int capacity = 1; while (capacity <initialCapacity) capacity <= 1 ;.................................. ........... return h & (length-1); // calculate the hash function

The most important concern in objects and HashMap is the equals and hashCode methods. Why does HashMap exist?Equals and hashCode contracts. This is because HashMap uses hashCode to store elements. Then, when get gets an element, it first finds the position through hashCode. Traverse the linked list at the position until key. equals (k) returns true. Therefore, if you override equals, you must override the corresponding hashCode.

            if (e.hash == hash &&                ((k = e.key) == key || (key != null && key.equals(k))))                return e;

After HashMap obtains the hashCode (variable h), a bunchRight Shift and exclusive operations. Why? H ^ = (h >>> 20) ^ (h >>>> 12); return h ^ (h >>> 7) ^ (h >>> 4 ); the above is the source code. This is equivalent to several distribution intervals of the int type. After the shift, h is moved to several distribution intervals, and then the XOR is merged. This is because HashMap requiresUniform DistributionHash Value. In one case, hashCode is mainly concentrated at a high level. When it is mapped to a bucket, hashCode & (length-1) is returned ). That isLow Position only. All elements must conflict. This is a terrible phenomenon. Therefore, this operation enables low-level hashCode to represent the random distribution of the entire hashCode.

        // This function ensures that hashCodes that differ only by        // constant multiples at each bit position have a bounded        // number of collisions (approximately 8 at default load factor).        h ^= (h >>> 20) ^ (h >>> 12);        return h ^ (h >>> 7) ^ (h >>> 4);

AboutCalculation of hashCode. First, the maximum expectation of hashCode is that the calculated value isRandom Distribution in int range. It is to map all possibilities to the entire int range. For example, long (int) (f ^ (f >>> 32 )). The second point must beConsidering the changes of all elements in the classFor example, the String calculation, s [0] * 31 ^ (n-1) + s [1] * 31 ^ (n-2) +... + s [n-1]. That is, for (int I = 0; I <len; I ++) h = 31 * h + val [off ++].

            char val[] = value;            for (int i = 0; i < value.length; i++) {                h = 31 * h + val[i];            }

Again, why is the String hashCode calculated?The base number is 31.What about it? Although the code size is not expected to be unique (because the calculation is usually very slow), do not repeat it as much as possible, soThe base should be as big as possible. In addition, 31 * N can be optimized by the compiler to move 5 digits left and then minus 1, which has high performance. The base isMust be a prime numberThe prime number feature (only 1 is a factor with itself) makes it easier to produce results after multiplying it with other numbers than other methods.UniquenessThat is, the minimum probability of conflict between hash code values.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.