Which is the better way to check if two BigDecimals are equal?Both methods 1 and 2 seem to work fine. And both are completely unreadable and ugly. Yet which one is better?
Another problem is with hash codes. If I try to do it like this:I get m == false. Because a and b have different scales, they also produce different hash code. Can you offer me a good way to get equal hash codes for a and b? This seems to work, but I'm not sure:
Rob Prime wrote:Equal hash codes does not necessarily mean equal objects. Keep that in mind. I wouldn't ever use hash code comparison for equality tests.
Neither would I.
My problem is this. Let's say I have a class MyClass which among other fields includes I want to override equals method, so I do:As far as I know, it's a good practice to override hashCode() together with equals. So I need a way to get hashCode of the "BigDecimal a" field in such way that it doesn't depend on BigDecimal's scale (so that my hashCode is compatible with my equals which doesn't use scale of the BigDecimals). If I just used a.hashCode(), there could be a case when to objects are equal, but have different hashCodes (due to the scale of BigDecimal).
In that case using stripZeros may be the best solution. If you are concerned about memory usage you can choose to cache the hash code:
That's what String does. Well, apart from the resetting to 0, but that's because String is immutable.