1、重写equals方法的两种方式,这里提供两个比较常见的equals重写方法:用instanceof实现重写equals方法; 用getClass实现重写equals方法。getClass()比instanceof更安全。接下来就是我们自己要来实现equals方法了。
package com.test;
import java.util.Objects;
class Rectangle {
private double length;
private double wide;
public Rectangle() {
//空实现
}
public Rectangle(double length, double wide) {
setLength(length);
setWide(wide);
}
public double getLength() {
return length;
}
public void setLength(double length) {
assert length > 0.0 : "您的输入有误,长方形的长不能小于0";
this.length = length;
}
public double getWide() {
return wide;
}
public void setWide(double wide) {
assert wide > 0.0 : "您的输入有误,长方形的宽不能小于0";
this.wide = wide;
}
public double area() {
return this.length * this.wide;
}
public double circumference() {
return 2 * (this.wide + this.length);
}
public boolean equals(Object obj) {
if (this == obj) { //判断一下如果是同一个对象直接返回true,提高效率
return true;
}
if (obj == null || obj.getClass() != this.getClass()) { //如果传进来的对象为null或者二者为不同类,直接返回false
return false;
}
//也可以以下方法:
// if (obj == null || !(obj instanceof Rectangle)) { //如果传进来的对象为null或者二者为不同类,直接返回false
// return false;
// }
Rectangle rectangle = (Rectangle) obj; //向下转型
//比较长宽是否相等,注意:浮点数的比较不能简单地用==,会有精度的误差,用Math.abs或者Double.compare
return Double.compare(rectangle.length, length) == 0 && Double.compare(rectangle.wide, wide) == 0;
}
public int hashCode() { //重写equals的同时也要重写hashCode,因为同一对象的hashCode永远相等
return Objects.hash(length, wide); //调用Objects类,这是Object类的子类
}
public String toString() {
return "Rectangle{" + "length=" + length + ", wide=" + wide + '}';
}
}
public class TestDemo {
public static void main(String[] args) {
Rectangle rectangle1 = new Rectangle(3.0, 2.0);
Rectangle rectangle2 = new Rectangle(3.0, 2.0);
System.out.println(rectangle1.equals(rectangle2));
System.out.println("rectangle1哈希码:" + rectangle1.hashCode() +
"\nrectangle2哈希码:" + rectangle2.hashCode());
System.out.println("toString打印信息:" + rectangle1.toString());
}
}
事实上两种方案都是有效的,区别就是getClass()限制了对象只能是同一个类,而instanceof却允许对象是同一个类或其子类,这样equals方法就变成了父类与子类也可进行equals操作了,这时候如果子类重定义了equals方法,那么就可能变成父类对象equlas子类对象为true,但是子类对象equlas父类对象就为false了。
网友评论