总结
在自定义中,重写hashCode()不需要加@Override.
因为Object.hashCode()并不是abstract函数。
在java中,hashCode()方法的主要作用是为了配合基于散列的集合一起正常运行,这样的散列集合包含HashSet、HashMap以及HashTable。
- 当你的自定义类Customer,要作为散列集合(HashSet、HashMap以及HashTable)的key时,就需要重写hashCode()方法。
- 不然,同一个Customer对象,哪怕其属性值发生了改变,其的hashCode始终一致。
- 因为在自定义类Customer没重写hashCode()时,其默认调用本地native方法 Object.hashCode(),同一个对象始终返回同一个hashCode
以我们最常用的HashMap为例,如果Customer不重写hashCode(), 很容易造成多个对象hash值相同,当这些对象在hashmap中当为key保存,其value会被“不经意”地覆盖。
不重写hashCode()
不重写时,hashCode 始终一致,所以往HashMap加入元素时,会覆盖前值
public class Solution { public static class Customer { private String username; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public static void main(String[] args) { System.out.println("打印对象Customer的hashCode值----------->"); HashMap<Customer, Integer> map = new HashMap<>(); Customer customer = new Customer(); System.out.println(customer.hashCode()); map.put(customer,1); customer.setAge(10); System.out.println(customer.hashCode()); map.put(customer,2); customer.setUsername("张三"); System.out.println(customer.hashCode()); map.put(customer,3); customer.setUsername("张"); System.out.println(customer.hashCode()); map.put(customer,4); customer.setAge(8); System.out.println(customer.hashCode()); map.put(customer,5); // size = 1 System.out.println("HashMap size ----------->" + map.size()); } }
输出:
打印对象Customer的hashCode值----------->
1761291320
1761291320
1761291320
1761291320
1761291320
HashMap size ----------->1
重写hashCode()
重写时,hashCode随着对象属性的改变而改变,所以往HashMap加入元素时,不会覆盖前值。
public class Solution { public static class Customer { private String username; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int hashCode(){ String temp = this.username + this.age; return temp.hashCode(); } } public static void main(String[] args) { System.out.println("打印对象Customer的hashCode值----------->"); HashMap<Customer, Integer> map = new HashMap<>(); Customer customer = new Customer(); System.out.println(customer.hashCode()); map.put(customer,1); customer.setAge(10); System.out.println(customer.hashCode()); map.put(customer,2); customer.setUsername("张三"); System.out.println(customer.hashCode()); map.put(customer,3); customer.setUsername("张"); System.out.println(customer.hashCode()); map.put(customer,4); customer.setAge(8); System.out.println(customer.hashCode()); map.put(customer,5); // size = 5 System.out.println("HashMap size ----------->" + map.size()); } }
输出:
打印对象Customer的hashCode值----------->
105180041
-1034385946
744669896
23403839
754968
HashMap size ----------->5