对类重写equals方法
用hashSet进行过滤必须在类中实现hashCode方法,因为每个hash表都是不相同的,所以,加入set
中就不会调用equals方法的。
// public boolean equals(Object obj) {
// System.out.println("2222222222222222");
// if (obj instanceof AA) {
// AA a = (AA) obj;
// if (this.name.equals(a.getName()) && (this.age == a.getAge()))
// return true;
// else
// return false;
// }else
// return false;
//}
//
//public int hashCode() {
// System.out.println("1111111111111111");
// return name.hashCode()+age;
//}
//
//public String toString() {
// return "name="+this.name+" age="+age;
//}
本文讲解了在Java中为自定义类正确实现equals方法和hashCode方法的重要性。为了确保对象能在HashSet等集合中正确地被识别为相等,必须同时覆盖这两个方法。文章通过示例代码展示了如何基于对象的属性来实现这两个方法。
6821

被折叠的 条评论
为什么被折叠?



