有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

/**
 * 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) 个答案

  1. # 1 楼答案

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

    如果Rational有一个构造函数接受一个int,我希望它提供一个默认分母1,因此使用您引用的方法计算哈希代码是完全合理的

    默认的Integer#hashCode()方法只是将整数本身作为散列码返回,因此返回的值将是0x000000010x000000250x00000024(36位小数)异或