何时覆盖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()方法实现 ...
随机推荐
- Pytest单元测试框架之parametrize参数化
1.参数化的本质:相同的步骤,但测试数据不同,比如登录的场景 import mathimport pytest# 方式一:分离出Listdef list_Test(): list = [ [2, 2, ...
- 使用vue-preview报错Cannot read property 'open' of undefined
最近在做一个vue项目中时,需要使用vue-preview插件制作缩略图,首先在终端使用npm i vue-preview -S指令安装了vue-preview插件,然后在main.js中,导入并引用 ...
- Cookie学习总结
Cookie简述 1. 概念 一种客户端会话技术,可以将一些少量的数据保存在客户端. 2. 快速使用 步骤 创建cookie对象,并设定数据 new Cookie(String name, Strin ...
- Guava - Map
创建Map 通常在创建map时使用new HashMap<>();的方法,guava提供了一个简洁的方法 Maps.newHashMap(); List转换Map List<Solu ...
- POJ3048
素数筛,数据范围不大,直接暴力筛. 坑:有个数据是 1 1,答案是1.差点没把我卡去世. 我的三观哪去了. #include<iostream> #include<cstdio> ...
- response 重定向
背景: controller层需要重定向到其他html界面时,需要用如下代码 // 设置302状态码 response.setStatus(302); // 设置location响应头 respons ...
- spring第三章
第三章 实现AOP AOP:面向方面编程,AOP能够使您将所有模块共有的特性与应用程序的主要业务逻辑隔离开 一.AOP介绍 横切关注点:在Web应用程序中,有一些服务(如登录.安全和事务管理)不是应用 ...
- maven 工程构建 之_____<dependencyManagement>标签
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave ...
- [JS]异步任务之事件循环
前言 常常会听到单线程和多线程这两个名词,单线程即一个时间段内程序从上到下执行任务,多线程即一个时间段内程序同时执行多个任务. 然而 JavaScript 是单线程的,它不像 Java 那样新开启一个 ...
- Vulnhub -- DC3靶机渗透
@ 目录 信息收集 尝试攻击 获取shell方法1 获取shell方法2 获取shell方法3 拿到root权限 拿FLAG 总结 信息收集 kali的ip为192.168.200.4,扫描出一个IP ...