如何重写hashCode()和equals()方法
hashCode()和equals()方法可以说是Java完全面向对象的一大特色.它为我们的编程提供便利的同时也带来了很多危险.这篇文章我们就讨论一下如何正解理解和使用这2个方法.
如何重写equals()方法
- It is reflexive: for any non-null reference value
x,x.equals(x)should returntrue. - It is symmetric: for any non-null reference values
xandy,x.equals(y)should returntrueif and only ify.equals(x)returnstrue. - It is transitive: for any non-null reference values
x,y, andz, ifx.equals(y)returnstrueandy.equals(z)returnstrue, thenx.equals(z)should returntrue. - It is consistent: for any non-null reference values
xandy, multiple invocations ofx.equals(y)consistently returntrueor consistently returnfalse, provided no information used inequalscomparisons on the objects is modified. - For any non-null reference value
x,x.equals(null)should returnfalse.
这段话用了很多离散数学中的术数.简单说明一下:
class Coder {
private String name;
private int age;
// getters and setters
}
我们想要的是,如果2个程序员对象的name和age都是相同的,那么我们就认为这两个程序员是一个人.这时候我们就要重写其equals()方法.因为默认的equals()实际是判断两个引用是否指向内存中的同一个对象,相当于 == . 重写时要遵循以下三步:
if(other == this)
return true;
if(!(other instanceof Coder))
return false;
Coder o = (Coder)other;
return o.name.equals(name) && o.age == age;
看到这有人可能会问,第3步中有一个强制转换,如果有人将一个Integer类的对象传到了这个equals中,那么会不会扔ClassCastException呢?这个担心其实是多余的.因为我们在第二步中已经进行了instanceof 的判断,如果other是非Coder对象,甚至other是个null, 那么在这一步中都会直接返回false, 从而后面的代码得不到执行的机会.
如何重写hashCode()方法
hashCode method whenever this method(equals) is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes."@Override
public int hashCode() {
int result = 17;
result = result * 31 + name.hashCode();
result = result * 31 + age; return result;
}
String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)"
重写equals()而不重写hashCode()的风险
Coder c1 = new Coder("bruce", 10);
Coder c2 = new Coder("bruce", 10);
1 @Override
2 public boolean equals(Object other) {
3 System.out.println("equals method invoked!");
4
5 if(other == this)
6 return true;
7 if(!(other instanceof Coder))
8 return false;
9
10 Coder o = (Coder)other;
11 return o.name.equals(name) && o.age == age;
12 }
Set<Coder> set = new HashSet<Coder>();
set.add(c1);
再执行:
System.out.println(set.contains(c2));
我们期望contains(c2)方法返回true, 但实际上它返回了false.
我让hashCode()每次都返回一个固定的数行吗
@Override
public int hashCode() {
return 10; }
如何重写hashCode()和equals()方法的更多相关文章
- 为什么要重写hashcode和equals方法?初级程序员在面试中很少能说清楚。
我在面试 Java初级开发的时候,经常会问:你有没有重写过hashcode方法?不少候选人直接说没写过.我就想,或许真的没写过,于是就再通过一个问题确认:你在用HashMap的时候,键(Key)部分, ...
- (转)为什么要重写 hashcode 和 equals 方法?
作者丨hsm_computer cnblogs.com/JavaArchitect/p/10474448.html 我在面试Java初级开发的时候,经常会问:你有没有重写过hashcode方法?不少候 ...
- HashMap中使用自定义类作为Key时,为何要重写HashCode和Equals方法
之前一直不是很理解为什么要重写HashCode和Equals方法,才只能作为键值存储在HashMap中.通过下文,可以一探究竟. 首先,如果我们直接用以下的Person类作为键,存入HashMap中, ...
- 为什么要重写hashcode和equals方法
我在面试 Java初级开发的时候,经常会问:你有没有重写过hashcode方法?不少候选人直接说没写过.我就想,或许真的没写过,于是就再通过一个问题确认:你在用HashMap的时候,键(Key)部分, ...
- 重写hashcode和equals方法
重写hashcode和equals方法 简乐君 2019-05-07 21:55:43 35481 收藏 191分类专栏: Java 文章标签: equals() hashcode()版权 一.前言我 ...
- 【转】 如何重写hashCode()和equals()方法
转自:http://blog.csdn.net/neosmith/article/details/17068365 hashCode()和equals()方法可以说是Java完全面向对象的一大特色.它 ...
- Java 重写 hashCode() 和 equals() 方法
1. hashCode 1.1 基本概念 hashCode 是 JDK 根据对象的地址算出来的一个 int 数字(对象的哈希码值),代表了该对象再内存中的存储位置. hashCode() 方法是超级类 ...
- 【java编程】重写HashCode和equals方法
[一]重写equals方案的规则 equals方法本来的原则 1.类的每个实例本质上都是唯一的. 2.不关心类是否提供了“逻辑相等”的测试功能 3.超类已经覆盖了equals,从超类继承过来的行为对于 ...
- Hibernate中用到联合主键的使用方法,为何要序列化,为何要重写hashcode 和 equals 方法
联合主键用Hibernate注解映射方式主要有三种: 第一.将联合主键的字段单独放在一个类中,该类需要实现java.io.Serializable接口并重写equals和hascode,再将该类注解为 ...
随机推荐
- python-django的生命周期
wsgi,请求封装后交给web框架(flask,django) 中间件,对请求进行校验或在请求对象中添加其他相关数据,列如(scrf[跨域],request,session) 路由匹配,根据浏览器发送 ...
- Day11作业及默写
1.写函数,传入n个数,返回字典{'max':最大值,'min':最小值} 例如:min_max(2,5,7,8,4) 返回:{'max':8,'min':2}(此题用到max(),min()内置函数 ...
- float浮动,定位
1 浮动定位 1.普通流定位 普通流,由称为文档流 块级元素:从上到下一个一个的排列 行内元素:一行内从左到右的排列 2.浮动定位 ...
- 记第十四届省赛参赛体会&第十三届
emmm....时间还是很久远了 还是流水账 这次比赛我还是挺开心的 因为感觉我们余神就是一把宝剑,然后我是她的Buff 前面四道题就挺顺利都1A过了,十年余神就是强无敌呀 最后两分钟过了第五题,银牌 ...
- Java知识汇总——思维导图
转载:https://www.cnblogs.com/java1024/p/8757952.html Java知识点汇总,从基础到常用的API.还有常用的集合类,总结的很详细.图片是从论坛里面找到的, ...
- Power BI与Tableau基于Google搜索上的比较
在数据分析领域里,不少的数据爱好者都会关心什么数据分析产品最好用?最重要的是,很多的企业也特别希望员工能真正知道如何使用这些BI平台以确保公司的投资是值得.同类的文章,小悦也曾发布过,可参考最近< ...
- js--call( )/apply()/bind()--应用
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call funct ...
- 【leetcode】344. Reverse String
problem 344. Reverse String solution: class Solution { public: void reverseString(vector<char> ...
- MongDB篇,第四章:数据库知识4
MongDB 数据库知识4 GridFS 大文件存储 文件的数据库存储 1,在数据库中以 字符串的方式 存储文件在本地的路径: 优点: 节省数据库空间 缺点: 当数据库或者文件位置发生变化时则无 ...
- C#正则表达式语法教程
C#语法之正则 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- 心分享.心创新!助力 ...