Exam Prep Sheet 8, HashCode Solution

If I understood everything correctly there is no implicit conversion from boolean to int in Java. However this is the overwritten Hashcode function for exercise 8.a: Hashing Pets on the Exam Prep Sheet:

@Override
public int hashCode() {
    return this.isPoisonous * 1000000 + this.weight * 1000 + this.length;
}

Which seems to require a conversion from boolean to int doesn’t it?
Thanks for your asnwers!

Jannik

1 Like

I’ve thrown the code into a compiler:

public static void main(String args[]) {
        int weight = 20;
        int length = 13;
        boolean isPoisonous = true;
        int hash = isPoisonous * 1000000 + weight * 1000 + length;
}

and the compiler has thrown the following error:

/MyClass.java:6: error: bad operand types for binary operator '*'
        int hash = isPoisonous * 1000000 + weight * 1000 + length;
                               ^
  first type:  boolean
  second type: int
1 error

This should be a mistake, I think.

1 Like

The hashCode function is fixed now. (and will show up shortly in the online version)
A simple way to convert a boolean b to an int is the ternary operator:
b ? 1 : 0 (read as: if b then 1 else 0)

Alternatively, if you understood hash codes and know what Java is doing, you can rely on the Objects.hash method from Java.