[Java Core]Java类的equals方法的实现
2015-09-12 09:54
573 查看
Java对equals方法的要求:
1. 自反性:x.equals(x) == true
2. 对称性:x.equals(y) == y.equals(x)
3. 传递性:
x.equals(y) == true && y.equals(z) == true => x.equals(z) == true
4. 一致性:若x,y均没有发生变化,x.equals(y)的结果不论调用多少次,都不发生变化
5. 非空结果:x.equals(null) == false
依据这几点要求,书中给出了一个完善的比较类的方法:
1. 自反性:x.equals(x) == true
2. 对称性:x.equals(y) == y.equals(x)
3. 传递性:
x.equals(y) == true && y.equals(z) == true => x.equals(z) == true
4. 一致性:若x,y均没有发生变化,x.equals(y)的结果不论调用多少次,都不发生变化
5. 非空结果:x.equals(null) == false
依据这几点要求,书中给出了一个完善的比较类的方法:
import java.util.Objects; public class Employee { public String member; public Object obj; public Employee(final String Member, final Object Obj){ member = Member; obj = Obj; } public boolean equals(Object otherObj){ //refer to same object, return true if(this == otherObj) return true; //otherObj is null, return false if(otherObj == null) return false; //belong to different class, return false if(this.getClass() != otherObj.getClass()) return false; //solve the problem of comparison between super obj and child obj if(!(otherObj instanceof Employee)) return false; Employee other = (Employee)otherObj; //in case obj or other.obj is null return Objects.equals(obj, other.obj) && member.equals(other.member); } }
相关文章推荐
- Java中可变长参数的使用及注意事项
- Java 异常处理 理解
- 简单介绍Java编程中的线程池
- 【Java多线程】-线程中断
- java 找不到或无法加载主类
- printStackTrace()输出和System.out输出非调用顺序输出
- JAVA编程的三个方向 笔记大纲
- 10个实用的但偏执的Java编程技术
- JAVA 安装环境变量配置
- Java设计模式模式观测(Observer Pattern)
- JVM(java 虚拟机)内存设置
- Spring MVC hello world annotation example
- 【小熊刷题】Letter Combinations of a Phone Number <Leetcode 17, Java>
- 【小熊刷题】3Sum Closest <Leetcode 16, Java>
- spring,cxf,restful发布webservice传递List,Map,List<Map>
- eclipse的svn插件出现问题,64位系统,解决方法
- java实现excel的导入导出(poi详解)
- Java实现简单的员工管理系统
- 【Java】正则表达式
- JavaSE值得注意的地方