国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

JDK源碼之解讀String最終類的equals()和hashcode()方法實現原理

2019-11-11 01:47:34
字體:
來源:轉載
供稿:網友
JDK源碼之解讀String最終類的equals()和hashcode()方法實現原理最近在看JDK源碼,先從簡單入手,比如 String類 ,List、Map和Set接口的實現類。。。

1,equals().

“abd”.equals(“abc”)采取的是兩字符串長度相等,在相等情況下,分別賦值給兩字節數組,循環數組,如對應位置兩數組值不相等,則return false;如都相等,則 return true. 源碼如下:

public boolean equals(Object anObject) {        if (this == anObject) {            return true;        }        if (anObject instanceof String){            String anotherString =(String) anObject;            int n = value.length;            if (n == anotherString.value.length) {                char v1[] = value;                char v2[] = anotherString.value;                int i = 0;                while (n-- != 0){                    if (v1[i] != v2[i])                            return false;                    i++;                }                return true;            }        }        return false;}

2, hashcode().

Stringstr=”ab”;

str.hashcode()==3105==(0*31+97)*31+98 //其中 97=a;98=b.   a對應的ascii碼=97。

把字符串分成字符數組,

用一個初始值為零的值,按公式 h=31*h+chararray[i] 在遍歷該字符串時候,重復計算,最后的h值就是該字符串數組的hashcode()返回值。  源碼如下:

public int hashCode() {        int h = hash;        if (h == 0 && value.length > 0) {            char val[] = value;            for (int i = 0; i < value.length; i++) {                h = 31 * h + val[i];            }            hash = h;        }        return h;    }


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 田阳县| 鄂托克旗| 穆棱市| 中山市| 阿瓦提县| 三穗县| 彩票| 英吉沙县| 贵港市| 永泰县| 江津市| 阳谷县| 安达市| 永胜县| 申扎县| 肃南| 奇台县| 金秀| 镇远县| 疏附县| 来凤县| 阳西县| 修武县| 德兴市| 辽源市| 郴州市| 上蔡县| 盖州市| 白玉县| 安国市| 东至县| 宣汉县| 收藏| 攀枝花市| 库尔勒市| 鲜城| 衡阳县| 遵义市| 罗源县| 临澧县| 德令哈市|