1. 程式人生 > >String的equals和hashCode方法

String的equals和hashCode方法

als bool str ins -- pan 因此 string類 ash

對於判斷對象是否相等,肯定需要重寫它的equals和hashCode方法。不然使用默認的方法只會比較地址,因此會出現錯誤。

以String類為例,且看它的equals方法

    public boolean equals(Object anObject) {
    //比較地址
    if (this == anObject) {
        return true;
    }
    //看是否是String實例
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        
int n = count; //比較字符串長度 if (n == anotherString.count) { char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; while (n-- != 0) { //比較字符是否相等 if (v1[i++] != v2[j++])
return false; } return true; } } return false; }

主要思想:比較地址、比較長度、比較字符

hsahCode實現方式:

    public int hashCode() {
    int h = hash;
        int len = count;
    if (h == 0 && len > 0) {
        int off = offset;
        char val[] = value;

            
for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; }

String的equals和hashCode方法