Skip to content
This repository has been archived by the owner on Jun 27, 2021. It is now read-only.

Commit

Permalink
JavaMoney/jsr354-ri/issues/146 Fixed hashCode/equals.
Browse files Browse the repository at this point in the history
  • Loading branch information
atsticks committed Jul 30, 2017
1 parent d3ec849 commit 92a2fa0
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/test/java/javax/money/convert/DefaultExchangeRate.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import javax.money.NumberValue;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Expand Down Expand Up @@ -247,7 +248,23 @@ public String toString() {
*/
@Override
public int hashCode() {
return Objects.hash(baseCurrency, conversionContext, factor, termCurrency, chain);
// Numerically equal factors should produce the same hash code, so hash a normalized
// version of the factor rather than the NumberValue object.
BigDecimal normalizedFactor = factor.numberValue(BigDecimal.class).stripTrailingZeros();

// The exchange rate chain includes a reference to "this" if the caller doesn't explicitly
// set a chain in the builder, so we can't naively hash the chain or we'll get infinite
// recursion.
int chainHash = 0;
for (ExchangeRate chainedRate : chain) {
if (chainedRate == this) {
// Use a constant to represent the presence of this object in the chain.
chainHash = Objects.hash(chainHash, "this");
} else {
chainHash = Objects.hash(chainHash, chainedRate);
}
}
return Objects.hash(baseCurrency, conversionContext, normalizedFactor, termCurrency, chainHash);
}

/*
Expand Down

0 comments on commit 92a2fa0

Please sign in to comment.