Home  >  Article  >  Java  >  HashCode method in Java and how to use it

HashCode method in Java and how to use it

WBOY
WBOYforward
2023-04-23 18:13:071653browse

Explanation

1. The hashcode method in java is a native method of the Object class, and the return value is of type int.

2. According to certain rules, the information related to the other party, such as the other party's storage address, the other party's fields, etc., is mapped to a value. This value is called a hash value.

Example

   public static int hashCode(int a[]) {
        if (a == null)
            return 0;
 
        int result = 1;
        for (int element : a)
            result = 31 * result + element;
 
        return result;
    }

The value 31 was chosen because it is an odd prime number. If it's an even number, the multiplication overflows and the information is lost, since multiplying by 2 equals shifting. The benefit of using prime numbers is less clear, but it is traditional. A nice feature of 31 is that multiplication can be replaced with shifts and subtractions for better performance: 31*i==(i<<5)-i. Modern virtual machines perform this optimization automatically.

The above is the detailed content of HashCode method in Java and how to use it. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete