equals() (javadoc) must define an equality 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().

Steps to Override equals method in Java

Here is my approach for overriding equals method in Java. This is based on standard approach most of Java programmer follows while writing equals method in Java.
 
1) Do this check -- if yes then return true.
2) Do null check -- if yes then return false.
3) Do the instanceof check,  if instanceof return false than return false from equals in Java , after some research I found that instead of instanceof we can use getClass() method for type identification because instanceof check returns true for subclass also, so its not strictly equals comparison until required by business logic. Butinstanceof check is fine if your class is immutable and no one is going to sub class it. For example we can replace instanceof check by below code
 
if((obj == null) || (obj.getClass() != this.getClass()))
        return false;
 
4) Type cast the object; note the sequence instanceof check must be prior to casting object.
 
5) Compare individual attribute starting with numeric attribute because comparing numeric attribute is fast and use short circuit operator for combining checks.  If first field does not match, don't try to match rest of attribute and return false. It’s also worth to remember doing null check on individual attribute before calling equals() method on them recursively to avoid NullPointerException during equals check in Java.

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 HashSetLinkedHashSetHashMapHashtable, 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的更多相关文章

  1. 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 ...

  2. Java之所有对象的公用方法>9.Always override hashCode when you override equals

     You must override hashCode in every class that overrides equals.

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

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

  4. C# abstract virtual override new finally java final finalize

    virtual:声明虚方法.可以被其派生类所重写的.重写方法需要使用override或者new关键字. override:覆盖原方法.可对重写virtual.override.abstract进行重写 ...

  5. 关于==和equals()方法&Java中string与char如何转换&String,StringBuffer

    1.对于基本数据类型,可以直接使用==和!=进行内容比较 如:int x=30;        int y=30;         x==y;  //true 基本数据类型 简单类型(基本类型) bo ...

  6. Overload and Override without Overwrite - Java

    Override(覆盖/覆写): 子类Override父类中的函数(方法).Overload(重载): 同一个类中包含多个同名的函数(方法), 但各个函数的参数列表不同. Override和Overl ...

  7. 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 ...

  8. Core Java Interview Question Answer

    This is a new series of sharing core Java interview question and answer on Finance domain and mostly ...

  9. 200个最常见的JAVA面试问题(附答案)

    本文内容: 20个最常见的JAVA面试问题(附答案) 13个单例模式JAVA面试问题(附答案) 说说JVM和垃圾收集是如何工作的(附答案) 说说如何避免JAVA线程死锁(附答案) Java中HashS ...

随机推荐

  1. 15个web前端的美轮美奂的 jQuery 图片特效

    jQuery是一个非常优秀的 JavaScript 框架,使用简单灵活,同时还有许多成熟的插件可供选择.其中,jQuery 最令人印象深刻的应用之一就是对图片的处理,它可以让帮助你在你的项目中加入各种 ...

  2. 华丽的HTML5/jQuery动画和应用 前端必备

    在网页应用中,我们经常会使用jQuery来实现一些简单的动画效果,比如菜单下拉时的渐变特效,图片滑动时的淡入淡出效果等.现在我们将jQuery和HTML5互相结合,让HTML5/CSS3强大的页面渲染 ...

  3. 配置PostgreSQL Streaming Replication集群

    运行环境: Primary: 192.168.0.11 Standby: 192.168.0.21, 192.168.0.22 OS: CentOS 6.2 PostgreSQL: 9.1.2 版本以 ...

  4. POJ 2407 Relatives

    Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 13920   Accepted: 6965 Description Give ...

  5. tar 「解/壓」 包

    1.tar: short read tar壓縮包文件發生了損壞,或者说不完整. 最近,在寫下載程序的時候,發生了這個問題.初步猜測文件寫完沒有關閉,沒有寫完.

  6. PSP编程初探 Hello World

    自己有一台PSP2000,玩了这么长时间的游戏,所以打算去探究一下PSP这个平台的程序的构建方式. 在网上搜了很多资料,感觉能用上的不多,毕竟这太小众了,通过自己的探索,总结了一下. 先搭建MinGW ...

  7. 记一次linux samba服务问题调试

    linux下samba服务加入windows域控后,samba共享名与合法用户名不应一致,否则无法访问此共享.

  8. C# 解析XML格式的字符串

    public CreateOrderReturnResult GetCreateOrderReturnApi() { var result = new CreateOrderReturnResult( ...

  9. Color About——First

    最近在Android开发学习中遇到TextView背景色以及文字颜色着色问题,在此做个记录. 首先对于颜色的选择,我推荐W3C School,上面有对网页颜色的详尽说明以及实例,还提供了对于,同一种颜 ...

  10. sublimetext2 中运行Python提示EOFError: EOF when reading a line

    解决方法:一.安装sublimeREPL    打开sublimeText2按CTRL+SHIFT+P,英文版输入:install后选择Package Control: Install Package ...