flash-boy

导航

 
public boolean equals(Object obj) {
    return (this == obj);
}

 

Object 中的 equals() 方法其实就是 ==,而 String 重写了 equals() 方法把它修改成比较两个字符串的值是否相等

public boolean equals(Object anObject) {
    // 对象引用相同直接返回true
    if (this == anObject) {
        return true;
    }
    // 判断需要对比的值是否为 String 类型,如果不是则直接返回 false
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            // 把两个字符串转化为 char 数组对比
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            // 循环比对两个字符串的每一字符
            while (n-- != 0) {
                // 如果其中一个字符不相等就返回false 若相等就继续比对
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

 

posted on 2022-08-23 11:59  flash-boy  阅读(33)  评论(0)    收藏  举报