为什么重写equals必须重写hashCode
equals常见面试题
在开始聊之前,我们先看几个常见的面试题,看看你能不能都回答上来。
- 1、equals和==有什么区别?
- 2、hashcode相等的两个对象一定==相等吗?equals相等吗?
- 3、两个对象用equals比较相等,那它们的hashcode相等吗?
如果我们不重写equals和hashcode,那么它使用的是Object方法的实现。我们先简单看一下
public boolean equals(Object obj) {
return (this == obj);
}
public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}
为什么要重写equals
通过以上代码可以看出,Object提供的equals在进行比较的时候,并不是进行值比较,而是内存地址的比较。由此可以知晓,要使用equals对对象进行比较,那么就必须进行重写equals。
重写equals不重写hashCode会存在什么问题
我们先看下面这段话
每个覆盖了equals方法的类中,必须覆盖hashCode。如果不这么做,就违背了hashCode的通用约定,也就是上面注释中所说的。进而导致该类无法结合所以与散列的集合一起正常运作,这里指的是HashMap、HashSet、HashTable、ConcurrentHashMap。
来自 Effective Java 第三版
结论:如果重写equals不重写hashCode它与散列集合无法正常工作。
既然这样那我们就拿我们最熟悉的HashMap来进行演示推到吧。我们知道HashMap中的key是不能重复的,如果重复添加,后添加的会覆盖前面的内容。那么我们看看HashMap是如何来确定key的唯一性的。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
查看代码发现,它是通过计算Map key的hashCode值来确定在链表中的存储位置的。那么这样就可以推测出,如果我们重写了equals但是没重写hashCode,那么可能存在元素重复的矛盾情况。
下面我们来演示一下
public class Employee {
private String name;
private Integer age;
public Employee(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(name, employee.name) &&
Objects.equals(age, employee.age);
}
/*@Override
public int hashCode() {
return Objects.hash(name, age);
}*/
}
public static void main(String[] args) {
Employee employee1 = new Employee("冰峰", 20);
Employee employee2 = new Employee("冰峰", 22);
Employee employee3 = new Employee("冰峰", 20);
HashMap<Employee, Object> map = new HashMap<>();
map.put(employee1, "1");
map.put(employee2, "1");
map.put(employee3, "1");
System.out.println("equals:" + employee1.equals(employee3));
System.out.println("hashCode:" + (employee1.hashCode() == employee3.hashCode()));
System.out.println(JSONObject.toJSONString(map));
}
按正常情况来推测,map中值存在两个元素,employee2和employee3。
执行结果

出现这种问题的原因就是因为没有重写hashCode,导致map在计算key的hash值的时候,绝对值相同的对象计算除了不一致的hash值。
接下来我们打开hashCode的注释代码,看看执行结果

总结
如果重写了equals就必须重写hashCode,如果不重写将引起与散列集合(HashMap、HashSet、HashTable、ConcurrentHashMap)的冲突。
为什么重写equals必须重写hashCode的更多相关文章
- 为什么重写equals还要重写hashcode??
equals和hashcode是object类下一个重要的方法,而object类是所有类的父类,所以所有的类都有这两个方法 equals和hashcode间的关系: 1.如果两个对象相同(即equal ...
- 【原创】关于java对象需要重写equals方法,hashcode方法,toString方法 ,compareto()方法的说明
在项目开发中,我们都有这样的经历,就是在新增表时,会相应的增加java类,在java类中都存在常见的几个方法,包括:equals(),hashcode(),toString() ,compareto( ...
- 为什么重写equals必须重写hoshCode的基础分析
为什么重写equals必须重写hoshCode的基础分析 1.我们先来了解下原生的equals和hashCode代码 原生equals:它判断的是两个对象是否相等 原生hashCode值:它是根据内存 ...
- 为什么要重写equals()方法与hashCode()方法
在java中,所有的对象都是继承于Object类.Ojbect类中有两个方法equals.hashCode,这两个方法都是用来比较两个对象是否相等的. 在未重写equals方法我们是继承了object ...
- Hibernate中为什么要重写equals方法和hashcode方法
1.*为什么要重写equals方法,首先我们来看一下equals源码: public boolean equals(Object anObject) { if (this == anObject) { ...
- 为什么重写equals()必须重写hashCode()
主要原因是因为hashCode是用对象的内部地址转换成一个整数的,而equals比较得是两个对象,或者是两个对象的内容 如果你重写了equals,而保留hashCode的实现不变,那么很可能两个对象明 ...
- JAVA正确地自定义比较对象---如何重写equals方法和hashCode方法
在实际应用中经常会比较两个对象是否相等,比如下面的Address类,它有两个属性:String province 和 String city. public class Address { priva ...
- JAVA 重写equals和重写hashCode
面试官可能会问你:“你重写过 hashcode 和 equals 么,为什么重写equals时必须重写hashCode方法?” 首先你需要了解: hashCode()的作用是获取哈希码(散列码) 它实 ...
- 为什么重写equals必须重写hashcode?
示例代码: class User { private String name; public User(String name) { this.name = name; } @Override pub ...
随机推荐
- palindrome-partitioning leetcode C++
Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...
- 【java+selenium3】特殊元素iframe的定位及详解(三)
一.iframe 内联框架 1.自己写个网页,仅供理解iframe演示使用,如下 <!DOCTYPE html> <html> <head> <meta ch ...
- testNG 注解使用说明
1.TestNG常用注解 @BeforeSuite 标记的方法:在某个测试套件(suite)开始之前运行 @BeforeTest 在某个测试(test)开始之前运行 @BeforeClass 在某个测 ...
- 『学了就忘』Linux基础命令 — 37、Linux中挂载操作的相关命令
目录 1.mount命令介绍 (1)mount命令说明 (2)mount命令格式 2.mount命令示例 3.mount -a命令说明 4.-o特殊选项说明 5.exec/noexec选项说明 挂载就 ...
- docker添加sudo权限
sudo groupadd docker # 添加group sudo gpasswd -a think docker # 添加用户到组 sudo service docker restart n ...
- Part 33 Angular nested scopes and controller as syntax
Working with nested scopes using $scope object : The following code creates 3 controllers - country ...
- LeetCode->链表反转
这是一个很基础的题目.今天处理了一下,不论是以双指针迭代.递归等方法,都能处理,但是也使这个题目更为典型. 剑指 Offer 24. 反转链表 - 力扣(LeetCode) (leetcode-cn. ...
- [loj6278]数列分块入门2
做法1 以$K$为块大小分块,并对每一个块再维护一个排序后的结果,预处理复杂度为$o(n\log K )$ 区间修改时将整块打上标记,散块暴力修改并归并排序,单次复杂度为$o(\frac{n}{K}+ ...
- Redis | 第4章 Redis中的数据库《Redis设计与实现》
目录 前言 1. Redis中的数据库 2. 数据库的键空间 3. 键的生成时间与过期时间 4. Redis中的过期键删除策略 5. AOF.RDB和复制功能对过期键的处理 5.1 生成 RDB 文件 ...
- python网络自动化运维paramiko实验
运行环境: 物理机:win10 1903 网络设备:EVE-NG模拟器上运行思科三层路由器 网络设备OS版本:cisco ios(versions 15.6) python环境:pycharm 3.5 ...