重写Object的equals方法
Object的equals比较两个对象是否相同,没有重写时比较的是内存地址是否相同(==)。
但我们有时候比较的是两个对象中的属性是否相同,
重写equals:
package cn.sasa.demo1; public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } //比较age是否相同 public boolean equals(Object obj) { //return this == obj; //比较内存地址 if(obj == null) { return false; } if(this == obj) { return true; } if(obj instanceof Person) { Person p = (Person)obj; return this.getAge() == p.getAge(); } return false; } }
package cn.sasa.demo1; public class Test { public static void main(String[] args) { Person p1 = new Person("sa", 12); Person p2 = new Person("sasa", 121); //p2 = p1; boolean b = p1.equals(p2); System.out.println(b); } }