The theory (for the language lawyers and the mathematically inclined):

equals() (javadoc) must define an equivalence relation (it must be reflexivesymmetric, 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), then a.hashCode() must be same as b.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 HashSetLinkedHashSetHashMapHashtable, 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()方法的更多相关文章

  1. 使用对象作为hashMap的键,需要覆盖hashcode和equals方法

    1:HashMap可以存放键值对,如果要以对象(自己创建的类等)作为键,实际上是以对象的散列值(以hashCode方法计算得到)作为键.hashCode计算的hash值默认是对象的地址值. 这样就会忽 ...

  2. JAVA中的各种 哈希码(HashCode) 与 equals方法在HIBERNATE的实际应用[转载]

    1.什么是哈希码(HashCode) 在Java中,哈希码代表对象的特征.例如对象 Java代码 String str1 = “aa”, str1.hashCode= 3104 String str2 ...

  3. 使用hashCode()和equals()方法 - Java

    在这篇文章中,我将指出我对hashCode()和equals()方法的理解.我将讨论它们的默认实现以及如何正确地覆盖它们.我还将使用Apache Commons包中的实用工具类来实现这些方法. has ...

  4. 为什么要重写hashcode和equals方法?初级程序员在面试中很少能说清楚。

    我在面试 Java初级开发的时候,经常会问:你有没有重写过hashcode方法?不少候选人直接说没写过.我就想,或许真的没写过,于是就再通过一个问题确认:你在用HashMap的时候,键(Key)部分, ...

  5. hashcode和equals方法的区别和联系

    说到 hashcode就要和Java中的集合,HashSet,HashMap 关系最为密切. 首先附录两张Java的集合结构图: 图二:(上图的简化版) 从Set集合的特点说起 & Set是如 ...

  6. (转)为什么要重写 hashcode 和 equals 方法?

    作者丨hsm_computer cnblogs.com/JavaArchitect/p/10474448.html 我在面试Java初级开发的时候,经常会问:你有没有重写过hashcode方法?不少候 ...

  7. hashcode和equals方法

    转自https://www.cnblogs.com/keyi/p/7119825.html 一.equals方法的作用 1.默认情况(没有覆盖equals方法)下equals方法都是调用Object类 ...

  8. 一、基础篇--1.1Java基础-hashCode和equals方法的区别和联系

     hashCode和equals方法的区别和联系  两个方法的定义 equals(Object obj)方法用来判断两个对象是否"相同",如果"相同"则返回tr ...

  9. 关于HashCode和equals方法在HashSet中的使用

    Object类是类层次结构的根类,故所有的类都是先该类的方法,其中HashCode()和equals()方法也是该类的方法. 1.HashCode()方法 Object类中HashCode()方法实现 ...

随机推荐

  1. EasyUI学后总结第一集

    1,创建Easyui组件-使用html还是使用js方式? 如果在创建Easyui组件的时候,组件再被更改,那么属于静态组件,对于静态组件不要使用js方式创建--会增加js代码量. 如果创建的Easyu ...

  2. python -- 模块与类库

    一.模块 模块(Module)是由一组类.函数和变量组成的,模块文件的扩展名是.py或.pyc 在使用模块之前,需要先使用import语句导入这个模块. 语法格式如下: import 模块名 from ...

  3. jsp-->js-->jsp之间的关系

    jsp和js通过form.submit();发送request请求createdIdSave.jsp 在CreatedIdSave.jsp中进行BL的增删改查操作,在jsp中将值保存到页面的scrip ...

  4. ajax 提交序列化表单

    1.提交序列化表单+参数: var a = $.param({'address':address,'delivity':delivity,'payment':payment}) + '&' + ...

  5. Tomcat7+ 弱口令 && 后台getshell漏洞

    打开tomcat管理页面http://192.168.49.2:8080/manager/html,输入弱密码tomcat:tomcat,即可访问后台 先将jsp大马压缩为zip,再将zip后缀改名为 ...

  6. js 跨域请求失败

    注:错误返回:Failed to load http://xxxxxxxxxxx: No 'Access-Control-Allow-Origin' header is present on the ...

  7. DC-9 靶机渗透测试

    DC-9 渗透测试 冲冲冲,好好学习 DC系列的9个靶机做完了,对渗透流程基本掌握,但是实战中出现的情况千千万万,需要用到的知识面太广了,学不可以已. 靶机IP: 172.66.66.139 kali ...

  8. 浏览器中hook对象属性

    先获取window对象属性 来源: 夜幕爬虫安全论坛 原文链接: http://bbs.nightteam.cn/thread-485.htm?orderby=desc&user=7

  9. Java异常02——自定义异常

    Error与Exception与自定义异常 Error与Exception Error Exception 自定义异常 快捷键: ctrl + alt + t  package exception.d ...

  10. Bugku-web-字符?正则?

    题目意思很明显,根据给出的规则构造出合理的正则表达式然后通过get方式提交弹出Flag. i:字体大小 /..../表示开始和结束. .号表示匹配0-9任一数字 *号表示重复前一个字符多次 {4,7} ...