JAVA equals函数

package Person;

public class Person {

    String name;
    int age;

    public Person() {
        // TODO Auto-generated constructor stub
    }

    public boolean equals(Object obj) {
        if (this == obj) { // 同一个对象:堆内存的同一块地址
            return true;
        }

        if (obj instanceof Person) { // obj对象是不是Person类型
            Person person = (Person) obj; // 向下转型
            // String是引用数据类型,需要使用equals比较
            if ((this.age == person.age) && (this.name.equals(person.name))) {
                return true;
            }
        } else {
            return false;
        }

        return false;
    }

}
package Person;

public class Test {

    public Test() {
        // TODO Auto-generated constructor stub
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Person person1 = new Person();
        Person person2 = new Person();
        Person person3 = new Person();

        person1.name = "furong";
        person1.age = 12;

        person2.name = "quange";
        person2.age = 12;

        person3.name = "furong";
        person3.age = 12;

        System.out.println(person1.equals(person2));
        System.out.println(person1.equals(person3));
    }

}

运行结果

false
true
posted @ 2020-09-08 13:10  thomas_blog  阅读(290)  评论(0编辑  收藏  举报