override equals in Java
equals()
(javadoc) must define an equality 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)
, then a.hashCode()
must be same as b.hashCode()
.
Steps to Override equals method in Java
return false;
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 Langlibrary. An example:
public class Person {
private String name;
private int age;
// ... public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
} public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (!(obj instanceof Person))
return false; Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
OR
/**
* Person class with equals and hashcode implementation in Java
* @author Javin Paul
*/
public class Person {
private int id;
private String firstName;
private String lastName; public int getId() { return id; }
public void setId(int id) { this.id = id;} public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } @Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
} Person guest = (Person) obj;
return id == guest.id
&& (firstName == guest.firstName
|| (firstName != null && firstName.equals(guest.getFirstName())))
&& (lastName == guest.lastName
|| (lastName != null && lastName .equals(guest.getLastName())));
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + id;
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
return result;
} }
Also remember:
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, orWeakHashMap, 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.
override equals in Java的更多相关文章
- Effective Java 09 Always override hashCode when you override equals
Failure to do so will result in a violation of the general contract for Object.hashCode, which will ...
- Java之所有对象的公用方法>9.Always override hashCode when you override equals
You must override hashCode in every class that overrides equals.
- 使用hashCode()和equals()方法 - Java
在这篇文章中,我将指出我对hashCode()和equals()方法的理解.我将讨论它们的默认实现以及如何正确地覆盖它们.我还将使用Apache Commons包中的实用工具类来实现这些方法. has ...
- C# abstract virtual override new finally java final finalize
virtual:声明虚方法.可以被其派生类所重写的.重写方法需要使用override或者new关键字. override:覆盖原方法.可对重写virtual.override.abstract进行重写 ...
- 关于==和equals()方法&Java中string与char如何转换&String,StringBuffer
1.对于基本数据类型,可以直接使用==和!=进行内容比较 如:int x=30; int y=30; x==y; //true 基本数据类型 简单类型(基本类型) bo ...
- Overload and Override without Overwrite - Java
Override(覆盖/覆写): 子类Override父类中的函数(方法).Overload(重载): 同一个类中包含多个同名的函数(方法), 但各个函数的参数列表不同. Override和Overl ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- Core Java Interview Question Answer
This is a new series of sharing core Java interview question and answer on Finance domain and mostly ...
- 200个最常见的JAVA面试问题(附答案)
本文内容: 20个最常见的JAVA面试问题(附答案) 13个单例模式JAVA面试问题(附答案) 说说JVM和垃圾收集是如何工作的(附答案) 说说如何避免JAVA线程死锁(附答案) Java中HashS ...
随机推荐
- 《HTML5与CSS3基础教程》学习笔记 ——Three Day
第十一章 1. box-sizing:border-box(让宽度和高度包含内边距和边框) 2. clear让后面的元素显示在浮动元素的后面 3. z-index只对只对绝对.固定.相对定位的元 ...
- 项目中Service层的写法
截取自项目中的一个service实现类,记录一下: base类 package com.bupt.auth.service.base; import javax.annotation.Resource ...
- 南阳理工ACM1076--方案数量
题目地址:http://acm.nyist.net/JudgeOnline/problem.php?pid=1076 分析: <span style="font-size:18px;& ...
- Nginx启动SSL功能,并进行功能优化,你看这个就足够了
一:开始Nginx的SSL模块 1.1 Nginx如果未开启SSL模块,配置Https时提示错误 nginx: [emerg] the "ssl" parameter requir ...
- 如何判断PHP 是ts还是nts版的
通过phpinfo(); 查看其中的 Thread Safety 项,这个项目就是查看是否是线程安全,如果是:enabled,一般来说应该是ts版,否则是nts版.
- CentOS安全设置
删除多余的用户和用户组,修改口令文件属性,禁止[Ctrl+Alt+Delete]重启命令,防止别人ping的方法.整理自互联网. 1.删除多余的用户和用户组 //删除多余用户 # vi /etc/pa ...
- 分享:perl 文件操作总结
发布:thebaby 来源:net [大 中 小] perl 文件操作,包括打开.关闭文件,读取.定入文件等.原文链接:http://www.jbxue.com/article/3153.html 打 ...
- php多层数组与对象的转换实例代码
通过json_decode(json_encode($object)可以将对象一次性转换为数组,但是object中遇到非utf-8编码的非ascii字符则会出现问题,比如gbk的中文,何况json_e ...
- apache 配置虚拟主机
1 打开httpd.conf 找到 # Virtual hosts #Include conf/extra/httpd-vhosts.conf [由于apache的版本不同,可能你ctrl+F ...
- phpcms v9 源码解析(3)pc_base::creat_app()
69 return self::load_sys_classs('application'); 在前面我们已经知道了,这个load_sys_classs 静态方法,它加载了P ...