equals()源码

equals():
ONE.重写了equal()的类
1.String
重写结果,比较的是字符串的内容是否相等
2.自定义类默认给出的重写方法(Student)
重写结果,比较自定义类的成员变量是否相同
TWO.没有重写equal()的类(使用的是object类中的equal方法)
1.StringBuffer

two.1.Object类中的equals的实现

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

one.1.String类中equls的实现

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;
    }

one.2.自定义类默认给出的equals重写方法

public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

posted @ 2019-05-31 14:59  那些年的代码  阅读(600)  评论(0编辑  收藏  举报