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

HashCode method in Java and how to use it

WBOY
Release: 2023-04-23 18:13:07
forward
1702 people have browsed it

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;
    }
Copy after login

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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template