怎么样设计Java中的类的相等性

p.setX(p.getX() + 1);
System.out.println(coll.contains(p)); // prints false (probably)

     java.lang.Object类中定义了equals方法,其所有的子类都可以进行重写。但是,有时候不适当的重写会导致一些错误,特别是在使用HashMap,HashSet等的时候。比如以下几种情况重写equals方法会产生不一致的行为:

1. 定义equals方法的时候,方法署名不对;

2.修改了equals方法,却没有修改hashCode方法;

3.使用变量来定义equals方法;

4.在父类和子类都定义equals方法是,

 

1.定义equals方法的时候,方法署名不对;比如有以下Point类:

class Point{
	private final int x;
	private final int y;
	public Point(int x,int y){
		this.x=x;
		this.y=y;
	}
	public int getX() {
		return x;
	}
	public int getY() {
		return y;
	}
}

 但是我们定义了一个错误的equals方法:

public boolean equals(Point other) {
  return (this.getX() == other.getX() && this.getY() == other.getY());
}

 咋看起来工作正常:

Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);
Point q = new Point(2, 3);

System.out.println(p1.equals(p2)); // prints true
System.out.println(p1.equals(q)); // prints false

但是我们我们把此类用在集合中,就会出现错误了:

HashSet<Point> coll = new HashSet<Point>();
coll.add(p1);

System.out.println(coll.contains(p2)); // prints false

      为什么集合中没有P2呢, p1和p2不是相等吗? 这里首先我们定义的equals方法不对,在Object中方法定义为equals(Object),而我们在这里定义成equals(Point point),这只是方法的重载,而不是方法的重写。当我们在使用equals方法时,是使用Point类定义的equals方法,而集合判断类型是否相等则调用Point类的equals(Object)方法。

假如我们有:

                     Object p2a = p2;
我们可以有以下结果:

                    

System.out.println(p1.equals(p2a)); // prints false

显而易见,p1和p2实际上是不相等的。

更好的equals方法:

@Override public boolean equals(Object other) {
    boolean result = false;
    if (other instanceof Point) {
        Point that = (Point) other;
        result = (this.getX() == that.getX() && this.getY() == that.getY());
    }
    return result;
}

这样的错我们一般不容易犯,因为大多数我们都使用IDE工具,很容易就可以察觉方法有没有重写父类的方法。但是我们重写了equals方法,还不能使coll.contains(p2)。原因是我们没有重写hashCode方法。

 

2,重写了equals方法,但是没有重写hashCode方法:

现在我们已经重写了equals方法,但是,我们定义俩个相等的Point实例,将其中一个放入HashSet中后,但是我们使用contains来测试另一个实例时,却可能得到false:

Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);

HashSet<Point> coll = new HashSet<Point>();
coll.add(p1);

System.out.println(coll.contains(p2)); // prints false  

     这里我们用的是HashSet,这意味这集合中的每一个元素都被放在一个个哈希桶中,至于放在那个桶中,是由对象的hashCode方法返回的值来确定的。这里我们使用contains方法来测试,它首先会通过p2返回的hashCode找到对应的桶,然后将它们俩个对象来比较。由于我们没有重写Object的hashCode方法,所以这里的Point对象依然使用Object方法的hashCode方法,显然它们不会有相同的hashCode。所以HashSet根据p2的到的hashCode根本找不到存放Point对象的桶。所以我们得出以上结果。

     在java.lang.Object类的hashCode方法中有以下描述:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

所以我们一般在重写了equals方法的同时重写hashCode方法。

public class Point {

    private final int x;
    private final int y;

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

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override public boolean equals(Object other) {
        boolean result = false;
        if (other instanceof Point) {
            Point that = (Point) other;
            result = (this.getX() == that.getX() && this.getY() == that.getY());
        }
        return result;
    }

    @Override public int hashCode() {
        return (41 * (41 + getX()) + getY());
    }
}

 

这仅仅是hashCode方法实现的一种。然而,这种设计还会存在错误的。

 

3.使用变量来定义equals方法:

class Point { 
    private int x;
    private int y;

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

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void setX(int x) { // Problematic
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    @Override 
    public boolean equals(Object other) {
        boolean result = false;
        if (other instanceof Point) {
            Point that = (Point) other;
            result = (this.getX() == that.getX() && this.getY() == that.getY());
        }
        return result;
    }
    
    @Override 
    public int hashCode() {
        return (41 * (41 + getX()) + getY());
    }
}

 这里我们声明的x,y为变量,且可以通过setter方法来修改变量的值。而且我们还使用了这俩个变量来定义equals方法和hashCode方法。当我们使用HashSet时,会的到一些奇怪的结果:

Point p = new Point(1, 2);
HashSet<Point> coll = new HashSet<Point>();
coll.add(p);
System.out.println(coll.contains(p)); // prints true

这里我们没有疑问,但是如果我们改变了x或y的值时,集合中是否还含有p呢?

p.setX(p.getX() + 1);
System.out.println(coll.contains(p)); // prints false 

我们却发现p不在集合中了,那p到那里取了呢?我们来测试下集合中的元素.

Iterator<Point> it = coll.iterator();
boolean containedP = false;
while (it.hasNext()) {
    Point nextP = it.next();
    if (nextP.equals(p)) {
        containedP = true;
        break;
    }
}

System.out.println(containedP); // prints true

 

我们集合中的有个元素和p是相等的,证明p包含在集合中,为什么contains会找不到呢?原因是我们定义的hashCode方法。当我们修改了对象的状态后,hashCode也就发生了变化,修改了的point对象的hashCode根本不能找到存放原point对象的哈希桶,所以会找不到p了。所以我们定义hashCode()方法得出的hashCode最好不要随对象的状态改变而改变。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值