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()); } }
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!