JAVA中复写equals方法

在JAVA中“==”用于比较两个引用对象的地址是否相同。但是如果我们想比较两个对象的内容是否相同,通常会覆写equals方法。equals方法用来比较两个对象的内容是否相等.

package org.lyk.entities;

public class Point
{
    private int x;
    private int y;

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + x;
        result = prime * result + y;
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (obj == null)
            return false;
        if (this == obj)
            return true;

        if (this.getClass() != obj.getClass())
            return false;

        Point point = (Point) obj;
        if (this.x == point.x && this.y == point.y)
            return true;
        else
            return false;

    }

}

上面的代码演示了覆写equals方法一般步骤。

  1. 比较第二个对象是否为空
  2. 比较两个对象的内存地址是否一致
  3. 比较两个对象的类型是否一致
  4. 比较两个对象的属性是否相同
package org.lyk.main;


import org.lyk.entities.*;

public class Main
{ 
    public static void main(String[] args)
    {  
        Point p1 = new Point(1, 2);
        Point p2 = new Point(1, 2);
        System.out.println(p1.equals(p2));
    }
}

上面的代码输出为true

上面的代码很好理解。但是倘若我们对Point做派生,也就是说现在有一个ColoredPoint类继承了Point,并且扩充了一个color属性,那么我们在派生类中的equals方法要增加两项:

  1. 调用super.equals()方法对父类相关属性的比较
  2. 在子类中增加对新增属性的比较
package org.lyk.entities;

public class ColoredPoint extends Point
{
    private String color;

    public ColoredPoint(int x, int y, String color)
    {
        super(x, y);
        this.color = color;
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean equals(Object obj)
    {
        if (obj == null)
            return false;
        if (this == obj)
            return true;
        if (!super.equals(obj))
            return false;

        if (this.getClass() != obj.getClass())
            return false;

        ColoredPoint cp = (ColoredPoint) obj;
        if (this.color == null && cp.color != null)
            return false;
        else if (!this.color.equals(cp.color))
            return false;
        else
            return true;

    }

}

下面是测试代码:

package org.lyk.main;


import org.lyk.entities.*;

public class Main
{ 
    public static void main(String[] args)
    {   
        ColoredPoint cp1= new ColoredPoint(1, 2, "RED");
        ColoredPoint cp2= new ColoredPoint(1, 2, "RED");
        System.out.println(cp1.equals(cp2)); 
    }
}