重写hashcode和equals
例如:
public class Person {
private String name;
private int age;
}
-
hashcode
定义初始值37,然后每次乘31加上属性值的hashcode方法。
public int hashcode() { int res = 37; res = 31 * res + (name != null?) name.hashcode(): 0; res = 31 * res + (age != null?) age.hashcode(): 0; return res; }
还可以直接调用Objects.hashcode()
public int hashcode() { int res = Objects.hash(name, age); }
但是注意:如果有了数组对象,需要对数组对象的所有内容单独调用hash,否则会有问题。
因为数组本身和数组本身是不同的,但是数组的元素相同,意思是:
int[] a = {1, 2}; int[] b = {1, 2}; System.out.println(a.hashCode()); System.out.println(b.hashCode()); // 结果: 681842940 1392838282 // 但是如果把每个元素都计算 System.out.println(ArrayHashCode(a)); System.out.println(ArrayHashCode(b)); public static int ArrayHashCode(int[] arr) { int res = 37; for (int i : arr) { res = res * 31 + Integer.hashCode(i); } return res; } // 结果 35590 35590 // 或者可以使用Arrays.hashcode()
-
equals
- 先判断是否指向的是同一个内存地址
- 在判断是否为空,或者类型不相同
- 如果类型相同,直接强制类型转换,比较属性值是否相同即可。
public boolean equals(Person that) { if (this == that) return true; if (that == null || that.getClass() != this.getClass()) return false; Person p = (Person) that; if (this.age != p.age) return false; return this.name == null? that.name == null: this.name.equals(that.name); }