本文介绍了如何以与比例无关的方式检查BigDecimal是否在Set或Map中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

BigDecimal的等于()方法也会比较比例,所以

BigDecimal's equals() method compares scale too, so

new BigDecimal("0.2").equals(new BigDecimal("0.20")) // false

这是为什么呢表现得像那样。

It's contested why it behaves like that.

现在,假设我有一个 Set< BigDecimal> 如何检查如果0.2在该集合中,则与比例无关?

Now, suppose I have a Set<BigDecimal>, how do I check if 0.2 is in that Set, scale independent?

Set<BigDecimal> set = new HashSet<>();
set.add(new BigDecimal("0.20"));
...
if (set.contains(new BigDecimal("0.2")) { // Returns false, but should return true
    ...
}


推荐答案

contains() HashSet 切换为。

contains() will work as you want it to if you switch your HashSet to a TreeSet.

与大多数人不同设置因为它将决定基于 compareTo()方法的相等性,而不是 equals() hashCode()

It is different from most sets as it will decide equality based on the compareTo() method as opposed to equals() and hashCode():

自比较不考虑比例,这正是你想要的。

And since BigDecimal.compareTo() compares without regard to scale, that's exactly what you want here.

或者您可以确保 Set 中的所有元素始终具有相同的最小比例使用( add()包含()):

Alternatively you could ensure that all elements in the Set are of the same, minimal scale, by always using stripTrailingZeros (both on add() and on contains()):

set.add(new BigDecimal("0.20").stripTrailingZeros());
...
if (set.contains(new BigDecimal("0.2").stripTrailingZeros()) {
  ...
}

这篇关于如何以与比例无关的方式检查BigDecimal是否在Set或Map中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 23:30