java的equals方法重写注意事项
来源:互联网 发布:php自动加载机制 编辑:程序博客网 时间:2024/04/30 08:16
java的equals方法一般情况下需要重写,以保证能够比较两个实例对象是否一致。
package chap09;import static java.lang.System.out;import java.util.Date;public class EqualsTest {public static void main(String[] args) {// TODO Auto-generated method stubout.println("successful");Employee e1 = new Employee();Employee e2 = new Employee();out.println(e1 == e2);out.println(e1.hashCode());out.println(e2.hashCode());}}class Employee implements Cloneable {@Overridepublic boolean equals(Object obj) {/** * equals must five steps: * 1:two variable are point to the same object. * 2:obj is null. * 3:variables is the same Class. * 4:cast obj. * 5:equals each field's value(== for primitive; equals for object). * */if (this == obj) {return true;}if ((obj == null) && (this.getClass() != obj.getClass())) {return false;}Employee other = (Employee)obj;return ((this.name.equals(other.name) &&(this.salary == other.salary) &&(this.hireDay.equals(other.hireDay))));}@Overridepublic Employee clone() throws CloneNotSupportedException {return (Employee)super.clone();}private String name;private double salary;private Date hireDay;}class Manager extends Employee {@Overridepublic boolean equals(Object obj) {/** * derived class's equals method have three steps to equals two objects. * 1:call the super object to equals with obj. * 2:cast obj. * 3:each field value, which are added in this class. * */if ( !super.equals(obj)) {return false;}Manager other = (Manager)obj;return (this.bonus == other.bonus);}private double bonus;}
0 0
- java的equals方法重写注意事项
- Java中重写equals方法的注意事项
- 重写equals方法的注意事项
- 重写equals方法的注意事项
- java通用方法equals、hashcode的重写注意事项
- Java 重写 equals 与 hashCode 的注意事项
- java equals方法的重写
- java:equals方法的重写
- Java中重写Object类的equals方法和hashcode方法的注意事项
- Java中重写Object类的equals方法和Hashcode方法的注意事项
- JAVA重写equals方法
- JAVA重写equals方法
- java 重写equals方法
- Java重写equals方法
- Java重写equals()方法
- java 重写equals()方法
- Java重写equals方法
- java 重写equals方法
- android animation 优秀文章
- 9508 诸葛给我牌
- 有效沟通-非暴力沟通
- 按键驱动程序设计笔记
- OS
- java的equals方法重写注意事项
- Unique Binary Search Trees II
- 轻松地集成动态条形码到Microsoft® Windows® Mobile, PocketPC的条码控件Mobile Barcode PocketPC DLL
- 8611 大牛之路I
- Activity
- In order to understandC++
- DB2数据库基础总结
- mysql 开启远程登录
- UML静态模型图