Home > Java > javaTutorial > How to use hashCode() in java

How to use hashCode() in java

王林
Release: 2023-05-21 22:49:06
forward
942 people have browsed it

1. The function of hashCode is to obtain the hash code, also called hash code. It actually returns an int integer. The purpose of this hash code is to determine the index position of the object in the hash table.

2. hashCode is defined in the Object class of JDK, which means that any class in Java contains the hashCode function.

Example

package com.tools;
 
import java.util.ArrayList;
 
 
public class HashCodeMeaning {
    public static void main(String[] args) {
        ArrayList list =  new ArrayList();
        int numberExist=0;
       
        //证明hashcode的值不是内存地址
        for (int i = 0; i < 10000; i++) {
            Object obj=new Object();
            if (list.contains(obj.toString())) {
                System.out.println(obj.toString() +"  exists in the list. "+ i);
                numberExist++;
            }
            else {
                list.add(obj.toString());
            }
        }
       
        System.out.println("repetition number:"+numberExist);
        System.out.println("list size:"+list.size());
       
        //证明内存地址是不同的。
        numberExist=0;
        list.clear();
        for (int i = 0; i < 10000; i++) {
            Object obj=new Object();
            if (list.contains(obj)) {
                System.out.println(obj +"  exists in the list. "+ i);
                numberExist++;
            }
            else {
                list.add(obj);
            }
        }
       
        System.out.println("repetition number:"+numberExist);
        System.out.println("list size:"+list.size());
    }
}
Copy after login

The above is the detailed content of How to use hashCode() in java. 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