Big numbers selfmade: Part 9/14: equals and hashCode
Every good immutable class should implement equals() and hashCode() from Object in a suitable (and compatible) way. In our case, we want two DecimalBigInt objects to be equals if they represent the same natural number.
This is, after our [normalization][Part 8: normalizing] equivalent to they have the same digits.
For our hashCode(), we simply sum up the digits, multiplying them with a small prime to make sure that digit-switching does not result in same hash code:
/**
* calculates a hashCode for this object.
*/
public final int hashCode() {
int hash = 0;
for(int digit : digits) {
hash = hash * 13 + digit;
}
return hash;
}
In the equals() method we simply can delegate to the compareTo method, instead of implementing the same algorithm again. But first we make sure that the other object is a DecimalBigInt, too.
/**
* compares this object with another object for equality.
* A DecimalBigInt is equal to another object only if this other
* object is also a DecimalBigInt and both represent the same
* natural number.
*/
public final boolean equals(Object o) {
return o instanceof DecimalBigInt &&
this.compareTo((DecimalBigInt)o) == 0;
}
Now we can use our DecimalBigInt-objects as keys in hash tables.
0: introduction, 1: number representation, 2: conversion from decimal format, 3: decimal formatting, 4: addition, 5: multiplication, 6: factorials, 7: comparison, 8: normalizing, 9: equals/hashCode, 10: converting between arbitrary radix systems, 11: converting from arbitrary radix, 12: division by small numbers, 13: conversion to arbitrary radix, 14: missing bits - Original question - Full code