何时覆盖hashCode()和equals()方法
The theory (for the language lawyers and the mathematically inclined):
equals() (javadoc) must define an equivalence relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.
hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).
The relation between the two methods is:
Whenever
a.equals(b), thena.hashCode()must be same asb.hashCode().
In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute equals() to compute hashCode().
Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:
public class Person {
private String name;
private int age;
// ...
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
Also remember:
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.
无论何时覆盖equals方法都需覆盖hashcode方法,并保持一致(equals为true, hashcode也一致),当需要把自己定义的类加到以hash的集合中时(HashMap会先比较hashcode, code一致时比较equals方法),如果要保持只有一个相同的实例时,需要覆盖这两方法。
何时覆盖hashCode()和equals()方法的更多相关文章
- 使用对象作为hashMap的键,需要覆盖hashcode和equals方法
1:HashMap可以存放键值对,如果要以对象(自己创建的类等)作为键,实际上是以对象的散列值(以hashCode方法计算得到)作为键.hashCode计算的hash值默认是对象的地址值. 这样就会忽 ...
- JAVA中的各种 哈希码(HashCode) 与 equals方法在HIBERNATE的实际应用[转载]
1.什么是哈希码(HashCode) 在Java中,哈希码代表对象的特征.例如对象 Java代码 String str1 = “aa”, str1.hashCode= 3104 String str2 ...
- 使用hashCode()和equals()方法 - Java
在这篇文章中,我将指出我对hashCode()和equals()方法的理解.我将讨论它们的默认实现以及如何正确地覆盖它们.我还将使用Apache Commons包中的实用工具类来实现这些方法. has ...
- 为什么要重写hashcode和equals方法?初级程序员在面试中很少能说清楚。
我在面试 Java初级开发的时候,经常会问:你有没有重写过hashcode方法?不少候选人直接说没写过.我就想,或许真的没写过,于是就再通过一个问题确认:你在用HashMap的时候,键(Key)部分, ...
- hashcode和equals方法的区别和联系
说到 hashcode就要和Java中的集合,HashSet,HashMap 关系最为密切. 首先附录两张Java的集合结构图: 图二:(上图的简化版) 从Set集合的特点说起 & Set是如 ...
- (转)为什么要重写 hashcode 和 equals 方法?
作者丨hsm_computer cnblogs.com/JavaArchitect/p/10474448.html 我在面试Java初级开发的时候,经常会问:你有没有重写过hashcode方法?不少候 ...
- hashcode和equals方法
转自https://www.cnblogs.com/keyi/p/7119825.html 一.equals方法的作用 1.默认情况(没有覆盖equals方法)下equals方法都是调用Object类 ...
- 一、基础篇--1.1Java基础-hashCode和equals方法的区别和联系
hashCode和equals方法的区别和联系 两个方法的定义 equals(Object obj)方法用来判断两个对象是否"相同",如果"相同"则返回tr ...
- 关于HashCode和equals方法在HashSet中的使用
Object类是类层次结构的根类,故所有的类都是先该类的方法,其中HashCode()和equals()方法也是该类的方法. 1.HashCode()方法 Object类中HashCode()方法实现 ...
随机推荐
- Hive——简介
Hive--简介 Hive 是基于 Hadoop 构建的一套数据仓库分析系统,它提供了丰富的 SQL 查询方式来分析存储在 Hadoop 分布式文件系统中的数据, 可以将结构化的数据文件映射为一张数据 ...
- MySQL8.0.26安装与卸载
一.安装 1.官网下载 百度进入官网,学习用社区版够了,我下的是压缩版点这直达下载页 据说8.X版本性能优化,比5.7版本快2倍! 接着,不登录直接下载 2.创建配置 下载完后,建议解压到一个没有中文 ...
- CSAPP:bomblab
BOMBLAB实验总结 CSAPP实验BOMB,很头疼,看不懂,勉强做完了. 答案是这样的: Border relations with Canada have never been better. ...
- Python在ubuntu16.04上环境搭建
1.anaconda3安装 mkdir anaconda cd anaconda wget https://repo.continuum.io/archive/Anaconda3-4.4.0-Linu ...
- mysql实现主从复制、读写分离的配置方法(二)
由于接触主从复制,读写分离的时间比较短,应用还不够熟练,目的是能通过MyCat实现基础的读写分离操作. 其核心功能是分库分表,配合数据库的主从模式还可实现读写分离. 1. 测试环境 一台win10主机 ...
- Python中调用Java程序包
<原创不易,转载请标明出处:https://www.cnblogs.com/bandaobudaoweng/p/10785766.html> 开发Python程序,需求中需要用到Java代 ...
- odoo12里面的RPC【远程过程调用】
odoo的RPC有两种:RPC API:1.xml-rpc 2.json-rpc 案例 x ...
- Qt Creator内qmake配置静态编译
起因 利用QT Creator编写一些纯C/C++应用,默认配置下是动态编译 解决 解决起来很简单,这里只是附上配置备忘;-) msvc: { QMAKE_CFLAGS_RELEASE += /MT ...
- 基于pygame框架的打飞机小游戏
import pygame from pygame.locals import * import time import random class Base(object): "" ...
- JSON数据的HTTP Header应该怎么标记?
第一种 header('Content-type: application/json'); 另一种 header('Content-type: text/json');