这个方法如何计算Rational(1).hashCode()? 1的分子或分母本身就是1

时间:2016-05-27 02:24:04

标签: java hash

/**
 * Returns a hash code for this Rational object.  That hash code is
 * derived from the hash codes for its two components.  This design
 * decision ensures that two Rational objects that are equal will have
 * the same hash code.
 * @return An integer hash code for this object
 */

public int hashCode() {
    return new Integer(num).hashCode() ^ (37 * new Integer(den).hashCode());
}

1 个答案:

答案 0 :(得分:1)

Rational不是标准Java的一部分。谷歌搜索显示它可能是外部库的一部分,但你没有告诉我们哪一个,所以我们无法真正说出它的行为。

如果Rational的构造函数只有一个int,我希望它提供1的默认分母,所以使用它计算哈希码是完全合理的。你引用的方法。

默认的Integer#hashCode()方法只返回整数本身作为哈希码,因此返回的值为0x00000001 xor'ed 0x000000250x00000024(36十进制)。