- 浏览: 81302 次
文章分类
- 全部博客 (89)
- web service (9)
- subversion (1)
- JBOSS (3)
- interview (23)
- jQery (2)
- ExtJs (0)
- Axis (0)
- Design pattern (3)
- Agile (2)
- mutithread (0)
- Core Java (24)
- programming methods (1)
- SSH (7)
- jee design (1)
- OO (4)
- books (8)
- other (1)
- JSF (7)
- seam (2)
- Weblogic (4)
- JPA (1)
- ADF (1)
- Spring (5)
- Tomcat (1)
- DWR (2)
- JEE (3)
- Servlet (1)
- EJB (1)
- JDBC (3)
最新评论
-
iloveflower:
呵呵。好好学习。。。。。。。。。。。。
java 读书 -
Eric.Yan:
看了一点,不过是电子版的……你这一说到提醒我了,还要继续学习哈 ...
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.
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.
发表评论
-
Java Collection summary
2012-06-16 02:40 581Collection:List、Set Map: ... -
When to use Comparable vs Comparator
2012-06-15 00:52 799I have a list of objects I need ... -
Arrays.fill with multidimensional array in Java
2012-06-15 00:09 704How can I fill a multidimension ... -
Immutable objects
2012-06-14 23:49 725Immutable objects are simply ... -
Implementing hashCode; Transaction.java
2012-06-14 23:43 833Below is the syntax highlight ... -
Lazy initialization
2012-06-14 22:48 807http://www.javapractices.com/to ... -
How to sort an array,mid of linkedlist, reverse int
2012-06-13 07:47 945A common mistake for a beginner ... -
Java各类型转换
2012-06-13 05:25 709各种数字类型转换成字符串型: String s = Str ... -
regular expression
2012-06-13 03:08 5211、Java对反斜线处理的 ... -
string functions
2012-06-13 00:09 857import java.util.*; public c ... -
String array to arraylist
2012-06-13 00:07 596There are some important thing ... -
core java interview summary
2012-06-12 04:11 390http://blog.sina.com.cn/s/blog_ ... -
programming with String
2012-06-12 01:43 559Question: 1) Write code to che ... -
OO Design books -good website
2012-06-07 03:13 701I’m always on the search on goo ... -
Write a String Reverser (and use Recursion!)
2012-06-07 03:03 527Java Interview questions: Write ... -
Java高手必会的要点
2012-05-29 03:28 617http://developer.51cto.com/art/ ... -
How to use getClass().getClassLoader().getResource()
2012-05-29 03:13 1762This is the simplest wat to get ... -
Top 30 Programming interview questions
2012-05-12 02:48 913Programming questions are integ ... -
10 example of using ArrayList in Java >>> Java ArrayList Tutorial
2012-05-12 02:37 886ArrayList in Java is most frequ ... -
How to use Comparator and Comparable in Java? With example
2012-05-12 02:21 779Read more: http://javarevisited ...
相关推荐
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 ...
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#: 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...
免费JAVA毕业设计 2024成品源码+论文+数据库+启动教程 启动教程:https://www.bilibili.com/video/BV1SzbFe7EGZ 项目讲解视频:https://www.bilibili.com/video/BV1Tb421n72S 二次开发教程:https://www.bilibili.com/video/BV18i421i7Dx
,IGBT结温估算 模型见另一个发布
"S7-200 PLC驱动的智能粮仓系统:带解释的接线图与组态画面原理详解",S7-200 mcgs基于plc的自动智能粮仓系统 带解释的梯形图接线图原理图图纸,io分配,组态画面 ,S7-200; PLC; 自动智能粮仓系统; 梯形图接线图; 原理图图纸; IO分配; 组态画面,基于S7-200 PLC的智能粮仓系统设计与实现
手机编程-1738391379497.jpg
,rk3399pro,rk3568,车载方案设计,4路AHD-1080P摄像头输入,防撞识别,助力车泥头车安全运输
,CAD、DXF导图,自动进行位置路径规划,源码可进行简单功能添加实现设备所需功能,已经在冲孔机,点胶机上应用,性价比超高。 打孔机实测一分钟1400个孔
,电机控制资料-- 注:本驱动器适合于直流有感无刷电机 功能特点 支持电压9V~36V,额定输出电流5A 支持电位器、开关、0~3.3V模拟信号范围、0 3.3 5 24V逻辑电平、PWM 频率 脉冲信号、RS485多种输入信号 支持占空比调速(调压)、速度闭环控制(稳速)、电流控制(稳流)多种调速方式 支持按键控制正反转速度,启停 特色功能 1. 霍尔自学习 电机的三相线和三霍尔信号线可不按顺序连接,驱动器可自动对电机霍尔顺序进行学习。 2. 稳速控制响应时间短 稳速控制时电机由正转2000RPM切为反转2000RPM,用时约1.0s,电机切过程平稳 3. 极低速稳速控制 电机进行极低速稳速控制,电机稳速控制均匀,无忽快忽慢现象。
《HFSS同轴馈电矩形微带天线的模型制作与参数优化:从结果中学习,使用HFSS软件包进行实践的详细教程》,HFSS同轴馈电矩形微带天线 天线模型,附带结果,可改参数,HFSS软件包 (有教程,具体到每一步,可以自己做出来) ,HFSS; 同轴馈电; 矩形微带天线; 可改参数; HFSS软件包; 附带结果; 教程,HFSS软件包:可改参微带天线模型附带结果教程
"基于第二篇文章求解方法,改进粒子群算法在微电网综合能源优化调度的应用与复现代码展示——第一篇模型的参考与实践",基于改进粒子群算法微电网综合能源优化调度 求解方法主要参考第二篇文章 模型参照第一篇 复现代码 ,核心关键词: 基于改进粒子群算法; 微电网综合能源优化调度; 求解方法; 第二篇文章; 模型; 第一篇文章; 复现代码;,基于第二篇求解方法的改进粒子群算法在微电网综合能源优化调度中的应用研究
基于Comsol模拟的三层顶板随机裂隙浆液扩散模型:考虑重力影响的瞬态扩散规律分析,Comsol模拟,考虑三层顶板包含随机裂隙的浆液扩散模型,考虑浆液重力的影响,模型采用的DFN插件建立随机裂隙,采用达西定律模块中的储水模型为控制方程,分析不同注浆压力条件下的浆液扩散规律,建立瞬态模型 ,Comsol模拟; 随机裂隙浆液扩散模型; 浆液重力影响; DFN插件; 达西定律模块储水模型; 注浆压力条件; 浆液扩散规律; 瞬态模型,Comsol浆液扩散模型:随机裂隙下考虑重力的瞬态扩散分析
"基于S7-200 PLC与MCGS组态的五层电梯控制系统设计与实现:带详细接线图、IO分配及组态画面解析",S7-200 PLC和MCGS组态5层电梯五层电梯PLC控制系统 带解释的梯形图接线图原理图图纸,io分配,组态画面 ,核心关键词:S7-200 PLC; MCGS组态; 五层电梯; PLC控制系统; 梯形图接线图; IO分配; 组态画面。,S7-200 PLC与MCGS组态五层电梯控制系统原理图及梯形图解析
一、项目简介 本项目是一套基于springBoot+mybatis+maven+vue夕阳红公寓管理系统 包含:项目源码、数据库脚本等,该项目附带全部源码可作为毕设使用。 项目都经过严格调试,eclipse或者idea 确保可以运行! 该系统功能完善、界面美观、操作简单、功能齐全、管理便捷,具有很高的实际应用价值 二、技术实现 jdk版本:1.8 及以上 ide工具:IDEA或者eclipse 数据库: mysql5.5及以上 后端:spring+springboot+mybatis+maven+mysql 前端: vue , css,js , elementui 三、系统功能 1、系统角色主要包括:管理员、用户 2、系统功能 主要功能包括: 用户登录注册 首页 个人中心 修改密码 个人信息 访客管理 公告信息管理 缴费管理 维修管理 行程轨迹管理 单页号类型管理 公告类型管理 维修类型管理 租客管理 轮播图管理 余额充值等功能 详见 https://flypeppa.blog.csdn.net/article/details/143117373
基于时空Transformer的端到端的视频注视目标检测.pdf
Online Retail.xlsx
,C#地磅称重无人值守管理软件。 软件实现功能: 1、身份证信息读取。 2、人证识别。 3、车牌识别(臻识摄像头、海康摄像头)。 4、LED显示屏文字输出。 5、称重仪数据。 6、二维码扫码。 7、语音播报。 8、红外对射功能。 9、道闸控制。
com.deepseek.chat.apk
基于pyqt5+OpenPose的太极拳姿态识别系统可视化界面python源码+数据集.zip,个人大三大作业设计项目、经导师指导并认可通过的高分设计项目,评审分99分,代码完整确保可以运行,小白也可以亲自搞定,主要针对计算机相关专业的正在做毕设的学生和需要项目实战练习的学习者,也可作为课程设计、期末大作业。 该压缩包是一个基于PyQt5和OpenPose技术的太极拳姿态识别系统的源代码和相关资源集合。系统能够实现对太极拳动作的实时姿态识别,并通过可视化界面展示出来,为学习和教学太极拳提供便利。 二、技术栈与组件 PyQt5:一个Python绑定的Qt库,用于创建图形用户界面(GUI)应用程序。它提供了丰富的组件和工具,可以方便地构建各种复杂界面,如按钮、文本框、图像视图等,同时也支持事件驱动编程,使得用户交互更加灵活。 OpenPose:一个来自卡内基梅隆大学(CMU)的开源库,主要用于人体、面部、手部以及脚部的关键点检测。它采用了深度学习的方法,能够在单张图片上实时估计多人的关节位置,对于运动分析、姿态识别等领域非常有用。