重寫Object的equals方法
阿新 • • 發佈:2018-12-12
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); } }