可变对象和hashCode [英] Mutable objects and hashCode

查看:113
本文介绍了可变对象和hashCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拥有以下课程:

public class Member {
private int x;
private long y;
private double d;

public Member(int x, long y, double d) {
    this.x = x;
    this.y = y;
    this.d = d;
}

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

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj instanceof Member) {
        Member other = (Member) obj;
        return other.x == x && other.y == y
                && Double.compare(d, other.d) == 0;
    }
    return false;
}

public static void main(String[] args) {
    Set<Member> test = new HashSet<Member>();
    Member b = new Member(1, 2, 3);
    test.add(b);
    System.out.println(b.hashCode());
    b.x = 0;
    System.out.println(b.hashCode());
    Member first = test.iterator().next();
    System.out.println(test.contains(first));
    System.out.println(b.equals(first));
           System.out.println(test.add(first));

}

}

它产生以下结果:

30814
29853
false
true
true

因为hashCode取决于对象的状态,所以不能再正确检索它,因此检查包含失败。 HashSet不再正常工作。一个解决方案是使成员不可变,但这是唯一的解决方案吗?是否所有添加到HashSet的类都是不可变的?有没有其他方法来处理这种情况?

Because the hashCode depends of the state of the object it can no longer by retrieved properly, so the check for containment fails. The HashSet in no longer working properly. A solution would be to make Member immutable, but is that the only solution? Should all classes added to HashSets be immutable? Is there any other way to handle the situation?

问候。

推荐答案

散列集中的对象要么要么是不可变的,你需要的在hashset(或hashmap)中使用它们之后,不要更改它们。

Objects in hashsets should either be immutable, or you need to exercise discipline in not changing them after they've been used in a hashset (or hashmap).

在实践中我很少发现这是一个问题 - 我很少发现自己需要使用复杂的对象,因为键是设置元素,当我这样做时,通常不是一个问题,只是不要改变它们。当然,如果你此时已经公开了对其他代码的引用,那么它会变得更难。

In practice I've rarely found this to be a problem - I rarely find myself needing to use complex objects as keys are set elements, and when I do it's usually not a problem just not to mutate them. Of course if you've exposed the references to other code by this time, it can become harder.

这篇关于可变对象和hashCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆