A Brief Introduction to the correct method for evaluating hashCode in Java and the value of hashcode

Source: Internet
Author: User

A Brief Introduction to the correct method for evaluating hashCode in Java and the value of hashcode

This article focuses on the relevant content of the correct hashCode Evaluate Method in Java, as detailed below.

The hash list has an optimization function to cache the hashCode of an object. If the hash code does not match, it will not check the equivalence of the object and be considered as different objects directly. If the hash code is equal, the system checks whether the object is equal (equals ).

If the object has the same hashCode, they will be mapped to the same hash bucket.If the hash code of all objects in the hash list is the same, the hash list will be degraded to a linked list, which greatly reduces the query efficiency.

A good hash function usually tends to "generate unequal hash codes for objects that do not want to wait ". Ideally, the hash function should evenly distribute instances that do not want to wait in the set to all possible hash columns, but it is very difficult to achieve this ideal situation, A simple and effective hashing method is provided below:

1. Store a non-zero constant value, such as 17, in an int type variable named result.

2. For each key domain f (Each domain involved in the equals Method) To complete the following steps:

  • Calculate hash code c of int type for this field
  • If the field is of the boolean type? 1: 0)
  • If the field is of the byte, char, short, or int type, (int) f)
  • If the field is of the long type, calculate (int) (f ^ (f >>> 32 ))
  • If the field is of the float type, Float. floatToIntBits (f) is calculated)
  • If this field is of the double type, Double. doubleToLongBits (f) is calculated, and the hash value is calculated based on the long value obtained in the preceding steps.
  • If the domain is an object reference and the equals method of this class compares its domain by recursively calling equals, then the hashCode is recursively called for this domain based on the above method.
  • If this field is an array, each element should be treated as a separate field and the above principle should be applied recursively. If every element in the array is important, Arrays can also be directly used. hashCode method.
  • Follow the formula below to merge hash code c obtained by the preceding steps into result in sequence:result = 31 * result + c; Multiplication is used to obtain a better hash function. For example, if the hash function of String omits multiplication, all strings with different alphabetic orders will have the same hash code. Here 31 is selected because it is an odd prime number. If the multiplier is an even number and the multiplication overflows, the information will be lost because the multiplication with 2 is equivalent to the displacement. The advantage of using prime numbers is not obvious, but it is customary to use prime numbers to calculate hash results. 31 has a good feature, that is, using shift and subtraction instead of multiplication can achieve better performance: 31 * I = (I <5)-I. The current VMS can automatically achieve this optimization.

If a class is immutable (all fields are final modified, and all fields are of the basic type or immutable class), and the overhead of calculating hash codes is relatively large, you should consider caching the hash code inside the object.

Public class HashCodeDemo {static class HashCodeClass {private final boolean bResult; private final byte byteValue; private final char charValue; private final short value; private final int intValue; private final long longValue; private final float floatValue; private final double doubleValue; private final String str; private final int [] arrayValue; // volatile indicates that the variable is accessed in the memory every time, to ensure that the variable is the latest pr Ivate volatile int hashCode; public HashCodeClass () {bResult = false; byteValue = 1; charValue = 'a'; struct value = 1; intValue = 1; longValue = 1l; floatValue = 1.0f; doubleValue = 1.0d; str = getClass (). getName (); arrayValue = new int [] {1, 2, 3, 4, 5 };}@ Override public int hashCode () {if (hashCode = 0) {// set a non-zero initial value to increase the conflicting int result of the zero domain to 17; // If the multiplier is omitted, all strings with different alphabetic order will have the same HASH code final int HASH. _ CODE = 31; result = HASH_CODE * result + (bResult? 1: 0); result = HASH_CODE * result + byteValue; result = HASH_CODE * result + charValue; result = HASH_CODE * result + expected value; result = HASH_CODE * result + intValue; result = HASH_CODE * result + (int) (longValue ^ (longValue >>> 32); result = HASH_CODE * result + Float. floatToIntBits (floatValue); long doubleLongValue = Double. doubleToLongBits (doubleValue); result = HASH_CODE * result + (in T) (doubleLongValue ^ (doubleLongValue >>> 32); result = HASH_CODE * result + (str = null? 0: str. hashCode (); System. out. println ("str =" + str + ", str. hashCode = "+ str. hashCode (); result = HASH_CODE * result + arrayValue. hashCode (); return result;} return hashCode;} public static void main (String [] args) {HashCodeClass obj = new HashCodeClass (); System. out. println ("obj. hashCode = "+ obj. hashCode (); System. out. println ("obj =" + obj. toString ());}}

Output

str=com.demo.test.HashCodeDemo$HashCodeClass, str.hashCode=-205823051obj.hashCode=946611167str=com.demo.test.HashCodeDemo$HashCodeClass, str.hashCode=-205823051obj=com.demo.test.HashCodeDemo$HashCodeClass@386c23df

Summary

The above is all about the correct value calculation method of hashCode in Java. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.