是另一个bigDecimal.toString()的BigDecimal总是等于?

and*_*dyf 11 java

在Java中,新的BigDecimal来自另一个bigDecimal.toString()总是等于?例如

    BigDecimal a = new BigDecimal("1.23");
    BigDecimal b = new BigDecimal(a.toString());

    System.out.println(a.compareTo(b) == 0); // always true?
Run Code Online (Sandbox Code Playgroud)

我知道BigDecimal是不可变的,但我想知道cloneBigDecimal对象是否有任何好的方法?

Sle*_*idi 17

是的,你可以这么认为.来自BigDecimal.toString文档

如果BigDecimal 使用BigDecimal(String)构造函数将该字符串表示转换回a ,则将恢复原始值.

但是,您可以安全地共享同一个对象,因为它immutable不需要复制


Gre*_*g D 6

只是备注:BigDecimal 不是最终的,因此它可以通过可变类进行扩展。因此,在某些用例中可能需要制作防御性副本。

可以使用 BigDecimal.toString() 方法:

 * There is a one-to-one mapping between the distinguishable
 * {@code BigDecimal} values and the result of this conversion.
 * That is, every distinguishable {@code BigDecimal} value
 * (unscaled value and scale) has a unique string representation
 * as a result of using {@code toString}.  If that string
 * representation is converted back to a {@code BigDecimal} using
 * the {@link #BigDecimal(String)} constructor, then the original
 * value will be recovered.
Run Code Online (Sandbox Code Playgroud)

下面是制作 BigDecimal 的防御性副本的代码示例:

public static BigDecimal safeInstance(BigDecimal val) { 
    return val.getClass() == BigDecimal.class ? 
    val : new BigDecimal(val.toString()); 
}
Run Code Online (Sandbox Code Playgroud)

但这有意义吗?如果一个类扩展了 BigDecimal 类,您无法确定它不会在不遵守约定的情况下扩展其 toString() 方法...

也许最好使 BigDecimal 的任何扩展无效:

public static BigDecimal safeInstance(BigDecimal val) { 
    if (val.getClass() != BigDecimal.class) {
        //TODO throw exception
    }
    return val; 
}
Run Code Online (Sandbox Code Playgroud)


小智 5

一种简单的方法是添加零

BigDecimal a = new BigDecimal("1.23");
BigDecimal b = a.add(BigDecimal.ZERO);
Run Code Online (Sandbox Code Playgroud)