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:
Generally to generate other hash codes.
Wouter Oet wrote:For what purpose do you need the hashCode?
Thanks for incredibly fast reply
Is something wrong with "a.stripTrailingZeros().equals(b.stripTrailingZeros())", or you just don't like it for readability/performance/style/etc. reasons?
Campbell Ritchie wrote:The stripTrailingZeroes method creates a new object, so might have a performance overhead against compareTo.
At which point this ceases to be "beginning" material and needs to move to another forum.
What about hash codes? Does it make sense to use stripTrailingZeroes when I want equal hash codes for BigDecimals with the same value but different scales?
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).