重写equals和hashCode
生活随笔
收集整理的這篇文章主要介紹了
重写equals和hashCode
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
equals()方法 1. 自反性:A.equals(A)要返回true. 2. 對稱性:如果A.equals(B)返回true, 則B.equals(A)也要返回true. 3. 傳遞性:如果A.equals(B)為true, B.equals(C)為true, 則A.equals(C)也要為true. 說白了就是 A = B , B = C , 那么A = C. 4. 一致性:只要A,B對象的狀態沒有改變,A.equals(B)必須始終返回true. 5. A.equals(null) 要返回false. //測試
public class Person {private int age;private String name;
@Overridepublic boolean equals(Object obj){if(this == obj){return true;}else if(!(obj instanceof Person)){return false;}else{Person p = (Person) obj;return p.name.equals(name) && p.age == age;}}@Overridepublic int hashCode(){int result = 17;result = result * 31 + age;result = result * 31 + name.hashCode();return result; }public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
//驗證,如果不重寫hashCode(),輸出false; public static void main(String[] args) {Person p = new Person();p.setAge(3);p.setName("ff");Person p1 = new Person();p1.setAge(3);p1.setName("ff");Set<Person> set = new HashSet<Person>(); set.add(p);System.out.println(set.contains(p1));} ?
public class Person {private int age;private String name;
@Overridepublic boolean equals(Object obj){if(this == obj){return true;}else if(!(obj instanceof Person)){return false;}else{Person p = (Person) obj;return p.name.equals(name) && p.age == age;}}@Overridepublic int hashCode(){int result = 17;result = result * 31 + age;result = result * 31 + name.hashCode();return result; }public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
//驗證,如果不重寫hashCode(),輸出false; public static void main(String[] args) {Person p = new Person();p.setAge(3);p.setName("ff");Person p1 = new Person();p1.setAge(3);p1.setName("ff");Set<Person> set = new HashSet<Person>(); set.add(p);System.out.println(set.contains(p1));} ?
?
轉載于:https://www.cnblogs.com/start-fxw/p/7299261.html
總結
以上是生活随笔為你收集整理的重写equals和hashCode的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 道宝演讲培训总结
- 下一篇: 说说WordPress的主查询函数-qu