[java] 更好的书写equals方法-汇率换算器的实现(4)
[java] 更好的书写equals方法-汇率换算器的实现(4)
[java] 更好的书写equals方法-汇率换算器的实现(4)
Table of Contents
- 1 系列文章地址
- 2 完美的一个equals方法应该包含的内容
- 3 将汇率转换器中的部份代码进行修改
1 系列文章地址
- java 汇率换算器的实现(1)
- java 汇率换算器的实现(2)
- java 汇率换算器实现-插曲1-正则表达式(1)
- java 汇率换算器的实现(3)
- java jsoup使用简介-汇率换算器实现-插曲2
- java 注释以及javadoc使用简介-汇率换算器的实现-插曲3
2 完美的一个equals方法应该包含的内容
- 首先判断两个对象是不是同一个对象
if (this == otherObject) return true;
- 当另一个对象为空时, 返回false
if (otherObject == null) return false;
- 比较的两个类的类型应该相同
if (getClass() != otherObject.getClass()) return false;
但是有一些人可能会使用下面的方式:
if (!(otherObject instanceof ThisClass)) return false;
这样会导致一个问题, 如:
// 父类 class People { public People(String name) { this.name = name; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; // if (getClass() != obj.getClass()) return false; if (!(obj instanceof People)) return false; People other = (People) obj; return name.equals(other.name); } private String name; } // 子类 class Student extends People { public Student(String name, String studentID) { super(name); this.studentID = studentID; } public boolean equals(Object obj) { if (!super.equals(obj)) return false; Student s = (Student) obj; return studentID == s.studentID; } private String studentID; }
当在main函数中运行下面的例子时, 就会抛出ClassCastException的异常
public class Demo { public static void main(String[] args) { People p1 = new People("zhang"); Student s1 = new Student("zhang", "ID1"); System.out.println(s1.equals(p1)); } }
因此在具体实现过程中建议使用:
if (getClass() != otherObject.getClass()) return false;
- 最后进行类型转换, 比较各个字段的大小
People other = (People) obj; return name.equals(other.name);
3 将汇率转换器中的部份代码进行修改
将Money类中的equals方法进行修改:
/** 当货币单位以及货币量都相等时, 两个货币对象就相等 @param obj 货币 @return 相等为true, 不相等为false*/ public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Money other = (Money) obj; return amount == other.amount && unit.equals(other.unit); }
Date: 2014-05-17 Sat
Org version 7.8.11 with Emacs version 24
Validate XHTML 1.0