溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何理解java中hashCode()

發(fā)布時間:2021-10-20 11:12:52 來源:億速云 閱讀:102 作者:iii 欄目:編程語言

這篇文章主要講解了“如何理解java中hashCode()”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“如何理解java中hashCode()”吧!

1、hashCode的作用是獲取哈希碼,也叫散列碼,實際上是返回int整數(shù)。該哈希碼的作用是確定該對象在哈希表中的索引位置。

2、hashCode定義在JDK的Object類中,這就意味著Java中的任何類都包含有hashCode 函數(shù)。

實例

package com.tools;
 
import java.util.ArrayList;
 
 
public class HashCodeMeaning {
    public static void main(String[] args) {
        ArrayList list =  new ArrayList();
        int numberExist=0;
       
        //證明hashcode的值不是內(nèi)存地址
        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());
       
        //證明內(nèi)存地址是不同的。
        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());
    }
}

感謝各位的閱讀,以上就是“如何理解java中hashCode()”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對如何理解java中hashCode()這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI