乘法表

时间:2014-07-06 11:21:56

标签: java set equals override

我正在制作乘法表(从2到9) - 这是10个随机生成的样本,例如

2 * 3 = 
4 * 5 = 
... (7 more times)
9 * 5 = 

要点是所有样品必须不同并且样品

5 * 8 = 

8 * 5 = 

被认为是相同的

我的想法是创建描述数字对的类对,覆盖它的等于方法,生成随机数,创建Pair并将Pair对象添加到Set。

public class Pair {
    private int first;
    private int second;

    public int getFirst() {
        return first;
    }

    public int getSecond() {
        return second;
    }

    public void setFirst(int first) {
        this.first = first;
    }

    public void setSecond(int second) {
        this.second = second;
    }

    public Pair() {}

    public Pair(int first, int second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || o.getClass() != this.getClass())
            return false;

        Pair that = (Pair) o;
        return (this.first == that.first && this.second == that.second) ||
                (this.second == that.first && this.first == that.second);
    }

    @Override
    public int hashCode() {
        int result = 17;
        int prime = 31;
        result = result * prime + first;
        result = result * prime + second;
        return result;
    }

    @Override
    public String toString() {
        return first + " * " + second + " =";
    }
}

public static Pair[] createTable(int count) {
        Random random = new Random();
        Set<Pair> set = new HashSet<Pair>();
        while (set.size() < count) {
            int first = random.nextInt(8) + 2;
            int second = random.nextInt(8) + 2;
            set.add(new Pair(first, second));
        }
        return set.toArray(new Pair[count]);
}

问题是方法createTable()返回的某些数组包含等价对 例如在

[7 * 6 =, 5 * 6 =, 4 * 8 =, 4 * 9 =, 2 * 8 =, 9 * 2 =, 8 * 2 =, 6 * 3 =, 5 * 2 =, 4 * 2 =]

有2 * 8和8 * 2对不应该在那里

哪里出错?

1 个答案:

答案 0 :(得分:4)

您的hashCode()方法错误。 hashCode() 必须为两个相等的对象返回相等的值。根据您的equals()方法,对5-7等于对7-5,但它们的hashCode()不一样。

要正确实施hashCode(),您应该始终以最低的数字开头:

public int hashCode() {
    int result = 17;
    int prime = 31;

    int lowest = first < second ? first : second;
    int highest = first < second ? second : first;

    result = result * prime + lowest;
    result = result * prime + highest;
    return result;
}

或更简单:

public int hashCode() {
    int lowest = first < second ? first : second;
    int highest = first < second ? second : first;
    return Objects.hash(lowest, highest);
}

或者,甚至更简单(感谢@ user2336315):

public int hashCode() {
    return Objects.hash(Math.min(first, second), Math.max(first, second));
}