`
iloveflower
  • 浏览: 81827 次
社区版块
存档分类
最新评论
  • iloveflower: 呵呵。好好学习。。。。。。。。。。。。
    java 读书
  • Eric.Yan: 看了一点,不过是电子版的……你这一说到提醒我了,还要继续学习哈 ...
    java 读书

How to override equals method in Java

 
阅读更多
Object class holds some very interesting method which is applicable at object level and one of them is equals () which we are going to discuss in this article. equals () method is used to compare the equality of two object. default implementation of equals() class provided by Object class compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object. JAVA recommends to override equals method if equality is going to be define by logical way or via some business logic and some classes in Java standard library does override it e.g. String class whose implementation of equals() method return true if content of two strings are exactly same.
java has provided a contract to follow while overriding equals () method which state that as per Java your equals()  method should adhere following rule:




1) Reflexive: Object must be equal to itself.

2) Symmetric: if a.equals(b) is true then b.equals(a) must be true.

3) Transitive: if a.equals(b) is true and b.equals(c) is true then c.equals(ad) must be true.

4) Consistent: multiple invocation of equals() method must result same value until any of properties are modified. So if two objects are equals in Java they will remain equals until any of there property is modified.

5) Null comparison: comparing any object to null must be false and should not result in NullPointerException. For example a.equals(null) must be false.




And equals method in Java must follow its commitment with hashcode as stated below.




1) If two objects are equal by equals() method then there hashcode must be same.

2) If two objects are unequal by equals() method then there hashcode could be same or different.




So this was the basic theory about equals () method in Java now we are going to discuss the approach on how to override equals () method, yes I know you all know this stuff but I have seen some of equals () code which can really be improved by following correct. For illustration purpose we will see an example of Person class and discuss How to write equals () method for that class.

Overriding 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 , 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. But instanceof 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 start with numeric attribute because comparing numeric attribute is fast and use short circuit operator for combining checks.  So 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.




Code Example of overriding equals method in Java

Let’s see a code example based on my approach of overriding equals method in Java as discussed in above paragraph:
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;            }

        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());
        }          
If you look above method we are first checking for "this" check which is fastest available check for equals method then we are verifying  whether object is null or not and object is of same type or not. only after verifying type of object we are casting it into desired object to  avoid any ClassCastException in Java. Also while comparing individual attribute we are comparing numeric attribute first ,using short circuit operator to avoid further calculation if its already unequal and doing null check on member attribute to avoid NullPointerException.

           

           

Common Errors while overriding equals in Java

Though equals and hashcode method are defined in Object class and one of fundamental part of Java programming I have seen many programmers making mistake while writing equals() method in Java. I recommend all Java programmer who has just started programming to write couple of equals and hashcode method for there domain or value object to get feel of it. Here I am listing some of common mistakes I have observed on various equals method in Java.



1) Instead of overriding equals() method programmer overloaded it.
This is the most common error I have seen while overriding equals method in Java. Syntax of equals method defined in Object class is public boolean equals(Object obj) but many people unintentionally overload equals method in Java by writing public boolean equals(Person obj), instead of using Object as argument they use there class name. This error is very hard to detect because of static binding. So if you call this method in your class object it will not only compile but also execute correctly but if you try to put your object in collection e.g. ArrayList and call contains() method which is based on equals() method in Java it will not able to detect your object. So beware of it.


2) Second mistake I have seen while overriding equals() method is not doing null check for member variables which ultimately results in NullPointerException during equals() invocation. For example in above code correct way of calling equals() method of member variable is after doing null check as shown below:

firstname == guest.firstname || (firstname != null && firstname.equals(guest.firstname)));


3) Third mistake I have seen is not overriding hashcode method in Java and only overriding equals() method. You must have to override both equals() and hashcode() method in Java , otherwise your value object will not be able to use as key object in HashMap because hashmap in based on equals() and hashcode to read more see , How HashMap works in Java
 
Writing JUnit tests for equals method in Java
Its good practice to write JUnit test cases to test your equals method. Here is my approach for writing JUnit test case for equals method in Java. I will write test cases to check equals behavior on different circumstances:

·          testReflexive() this method will test reflexive nature of equals() method in Java.

·          testSymmeteric() this method will verify symmetric nature of equals() method in Java.

·          testNull() this method will verify null comparison and will pass if equals method returns false.

·          testConsistent() will verify consistent nature of equals method in Java.

·          testNotEquals() will verify if two object which are not supposed to equals is actually not equal

·          testHashcode() will verify that if two objects are equal by equals() method in Java then there hashcode must be same.




5 Tips on Equals method in Java




Tip: most of the IDE provides support to generate equals() and hashcode() method

In Eclipse do the right click-> source -> generate hashCode() and equals().

Tip: if your domain class has any unique business key then just comparing that field in equals method would be enough instead of comparing all the fields e.g. in case of our example if "id" is unique for every person then by just comparing id we will be able to identify whether two persons are equal or not.

Tip: while overriding hashcode method in Java makes sure you use all fields which have been used while writing equals method in Java.

Tip: String and Wrapper classes in java override equals method but StringBuffer doesn’t override it.

Tip: Whenever possible try to make your fields immutable, equals method based on immutable fields are much secure than equals method based on mutable fields.

分享到:
评论

相关推荐

    Google C++ Style Guide(Google C++编程规范)高清PDF

    How can we use a class Foo in a header file without access to its definition? We can declare data members of type Foo* or Foo&. We can declare (but not define) functions with arguments, and/or ...

    java面试宝典

    196、Can a database connection pool be instantiated in init method of servlet instead of server connection pool? What will be the problem? 46 综合部分 46 197、Class.forName的作用?为什么要用? 47 198、...

    Effective C#

    ### Effective C#: Key Insights and Best Practices #### Introduction "Effective C#" is an invaluable resource for developers ...- **Pattern:** Events allow objects to notify other objects of changes in...

    智能家居_物联网_环境监控_多功能应用系统_1741777957.zip

    人脸识别项目实战

    PLC热反应炉仿真程序和报告 ,PLC; 热反应炉; 仿真程序; 报告,PLC热反应炉仿真程序报告

    PLC热反应炉仿真程序和报告 ,PLC; 热反应炉; 仿真程序; 报告,PLC热反应炉仿真程序报告

    C++函数全解析:从基础入门到高级特性的编程指南

    内容概要:本文详细介绍了 C++ 函数的基础概念及其实战技巧。内容涵盖了函数的基本结构(定义、声明、调用)、多种参数传递方式(值传递、引用传递、指针传递),各类函数类型(无参无返、有参无返、无参有返、有参有返),以及高级特性(函数重载、函数模板、递归函数)。此外,通过实际案例展示了函数的应用,如统计数组元素频次和实现冒泡排序算法。最后,总结了C++函数的重要性及未来的拓展方向。 适合人群:有一定编程基础的程序员,特别是想要深入了解C++编程特性的开发人员。 使用场景及目标:① 学习C++中函数的定义与调用,掌握参数传递方式;② 掌握不同类型的C++函数及其应用场景;③ 深入理解函数重载、函数模板和递归函数的高级特性;④ 提升实际编程能力,通过实例强化所学知识。 其他说明:文章以循序渐进的方式讲解C++函数的相关知识点,并提供了实际编码练习帮助理解。阅读过程中应当边思考边实践,动手实验有助于更好地吸收知识点。

    `计算机视觉_Python_PyQt5_Opencv_综合图像处理与识别跟踪系统`.zip

    人脸识别项目实战

    Ultra Ethernet Consortium规范介绍与高性能AI网络优化

    内容概要:本文主要介绍了Ultra Ethernet Consortium(UEC)提出的下一代超高性能计算(HPC)和人工智能(AI)网络解决方案及其关键技术创新。文中指出,现代AI应用如大型语言模型(GPT系列)以及HPC对集群性能提出了更高需求。为了满足这一挑战,未来基于超乙太网络的新规格将采用包喷射传输、灵活数据报排序和改进型流量控制等机制来提高尾部延迟性能和整个通信系统的稳定度。同时UEC也在研究支持高效远程直接内存访问的新一代协议,确保能更好地利用现成以太网硬件设施的同时还增强了安全性。 适合人群:网络架构师、数据中心管理员、高性能运算从业人员及相关科研人员。 使用场景及目标:①为构建高效能的深度学习模型训练平台提供理论指导和技术路线;②帮助企业选择最合适的网络技术和优化现有IT基础设施;③推动整个行业内关于大规模分布式系统网络层面上的设计创新。 阅读建议:本文档重点在于展示UEC如何解决目前RDMA/RoCE所面临的问题并提出了一套全新的设计理念用于未来AI和HPC环境下的通信效率提升。在阅读时需要注意理解作者对于当前网络瓶颈分析背后的原因以及新设计方案所能带来的具体好处

    (参考GUI)MATLAB道路桥梁裂缝检测.zip

    (参考GUI)MATLAB道路桥梁裂缝检测.zip

    pygeos-0.14.0-cp311-cp311-win-amd64.whl

    pygeos-0.14.0-cp311-cp311-win_amd64.whl

    微信小程序_人脸识别_克隆安装_社交娱乐用途_1741777709.zip

    人脸识别项目实战

    基于Matlab的模拟光子晶体光纤中的电磁波传播特性 对模式场的分布和有效折射率的计算 模型使用有限差分时域(FDTD)方法来求解光波在PCF中的传播模式 定义物理参数、光纤材料参数、光波参数、PC

    基于Matlab的模拟光子晶体光纤中的电磁波传播特性 对模式场的分布和有效折射率的计算 模型使用有限差分时域(FDTD)方法来求解光波在PCF中的传播模式 定义物理参数、光纤材料参数、光波参数、PCF参数及几何结构等参数 有限差分时域(FDTD)方法:这是一种数值模拟方法,用于求解麦克斯韦方程,模拟电磁波在不同介质中的传播 特征值问题求解:使用eigs函数求解矩阵的特征值问题,以确定光波的传播模式和有效折射率 模式场分布的可视化:通过绘制模式场的分布图,直观地展示光波在PCF中的传播特性 程序已调通,可直接运行 ,基于Matlab模拟; 光子晶体光纤; 电磁波传播特性; 模式场分布; 有效折射率计算; 有限差分时域(FDTD)方法; 物理参数定义; 几何结构参数; 特征值问题求解; 程序运行。,基于Matlab的PCF电磁波传播模拟与特性分析

    知识图谱与大模型融合实践研究报告:技术路径、挑战及行业应用实例分析

    内容概要:《知识图谱与大模型融合实践研究报告》详细探讨了知识图谱和大模型在企业级落地应用的现状、面临的挑战及融合发展的潜力。首先,介绍了知识图谱与大模型的基本概念和发展历史,并对比分析了两者的优点和缺点,随后重点讨论了两者结合的可行性和带来的具体收益。接下来,报告详细讲解了两者融合的技术路径、关键技术及系统评估方法,并通过多个行业实践案例展示了融合的实际成效。最后提出了对未来的展望及相应的政策建议。 适合人群:对人工智能技术和其应用有兴趣的企业技术人员、研究人员及政策制定者。 使用场景及目标:①帮助企业理解知识图谱与大模型融合的关键技术和实际应用场景;②指导企业在实际应用中解决技术难题,优化系统性能;③推动相关领域技术的进步和发展,为政府决策提供理论依据。 其他说明:报告不仅强调了技术和应用场景的重要性,还关注了安全性和法律法规方面的要求,鼓励各界积极参与到这项新兴技术的研究和开发当中。

    (参考GUI)MATLAB BP神经网络的火焰识别.zip

    神经网络火焰识别,神经网络火焰识别,神经网络火焰识别,神经网络火焰识别,神经网络火焰识别

    人脸识别_实时_ArcFace_多路识别技术_JavaScr_1741771263.zip

    人脸识别项目实战

    telepathy-farstream-0.6.0-5.el7.x64-86.rpm.tar.gz

    1、文件内容:telepathy-farstream-0.6.0-5.el7.rpm以及相关依赖 2、文件形式:tar.gz压缩包 3、安装指令: #Step1、解压 tar -zxvf /mnt/data/output/telepathy-farstream-0.6.0-5.el7.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm 4、更多资源/技术支持:公众号禅静编程坊

    基于Springboot框架的购物推荐网站的设计与实现(Java项目编程实战+完整源码+毕设文档+sql文件+学习练手好项目).zip

    本东大每日推购物推荐网站管理员和用户两个角色。管理员功能有,个人中心,用户管理,商品类型管理,商品信息管理,商品销售排行榜管理,系统管理,订单管理。 用户功能有,个人中心,查看商品,查看购物资讯,购买商品,查看订单,我的收藏,商品评论。因而具有一定的实用性。 本站是一个B/S模式系统,采用Spring Boot框架作为开发技术,MYSQL数据库设计开发,充分保证系统的稳定性。系统具有界面清晰、操作简单,功能齐全的特点,使得东大每日推购物推荐网站管理工作系统化、规范化。 关键词:东大每日推购物推荐网站;Spring Boot框架;MYSQL数据库 东大每日推购物推荐网站的设计与实现 1 1系统概述 1 1.1 研究背景 1 1.2研究目的 1 1.3系统设计思想 1 2相关技术 3 2.1 MYSQL数据库 3 2.2 B/S结构 3 2.3 Spring Boot框架简介 4 3系统分析 4 3.1可行性分析 4 3.1.1技术可行性 5 3.1.2经济可行性 5 3.1.3操作可行性 5 3.2系统性能分析 5 3.2.1 系统安全性 5 3.2.2 数据完整性 6 3.3系统界面

    使用C语言编程设计实现的平衡二叉树的源代码

    二叉树实现。平衡二叉树(Balanced Binary Tree)是一种特殊的二叉树,其特点是树的高度(depth)保持在一个相对较小的范围内,以确保在进行插入、删除和查找等操作时能够在对数时间内完成。平衡二叉树的主要目的是提高二叉树的操作效率,避免由于不平衡而导致的最坏情况(例如,形成链表的情况)。本资源是使用C语言编程设计实现的平衡二叉树的源代码。

    基于扩张状态观测器eso扰动补偿和权重因子调节的电流预测控制,相比传统方法,增加了参数鲁棒性 降低电流脉动,和误差 基于扩张状态观测器eso补偿的三矢量模型预测控制 ,基于扩张状态观测器; 扰动补

    基于扩张状态观测器eso扰动补偿和权重因子调节的电流预测控制,相比传统方法,增加了参数鲁棒性 降低电流脉动,和误差 基于扩张状态观测器eso补偿的三矢量模型预测控制 ,基于扩张状态观测器; 扰动补偿; 权重因子调节; 电流预测控制; 参数鲁棒性; 电流脉动降低; 误差降低; 三矢量模型预测控制,基于鲁棒性增强和扰动补偿的电流预测控制方法

Global site tag (gtag.js) - Google Analytics