在 Java 中声明 BigDecimal 数组的初始值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20683665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:34:49  来源:igfitidea点击:

Declare Initial Value of BigDecimal Array in Java

javaarraysbigdecimal

提问by ray

I want to declare a BigDecimalArraywith initial value 0like this:

我想BigDecimalArray用这样的初始值声明一个0

BigDecimal[] val = {0,0,0};

but it's not working. Please help me to know how to declare BigDecimalarraywith initial value.

但它不起作用。请帮助我知道如何BigDecimalarray使用初始值进行声明。

采纳答案by Peter Lawrey

I would use Arrays.fill() as that will would for any number of zeros (or any other BigDecimal value you like) This works because BigDecimal is immutable, don't do this for mutable values ;)

我会使用 Arrays.fill() ,因为这将用于任意数量的零(或您喜欢的任何其他 BigDecimal 值)这是有效的,因为 BigDecimal 是不可变的,不要对可变值这样做;)

BigDecimal[] val = new BigDecimal[N];
Arrays.fill(val, BigDecimal.ZERO);

回答by Tim B

BigDecimal[] val = {new BigDecimal(0),new BigDecimal(0),new BigDecimal(0)};

BigDecimal is an object, not a primitive type, so you need to create new instances of the object in order to fill an array with them.

BigDecimal 是一个对象,而不是原始类型,因此您需要创建该对象的新实例,以便用它们填充数组。

It's no different from if you do:

这与如果你这样做没有什么不同:

BigDecimal val = 0;  // Fails
BigDecimal val = new BigDecimal(0);  // Succeeds

回答by Konstantin Yovkov

You can use the predefined BigDecimal.ZEROconstant:

您可以使用预定义的BigDecimal.ZERO常量:

BigDecimal[] val = { BigDecimal.ZERO,
                    BigDecimal.ZERO,
                    BigDecimal.ZERO };

回答by René Link

You can use Arrays.fill(Object[], Object)with BigDecimal.ZERO, because BigDecimal's are immutable. Thus you don't need to create a new instance for every array element.

您可以使用Arrays.fill(Object[], Object)with BigDecimal.ZERO,因为BigDecimal's 是不可变的。因此您不需要为每个数组元素创建一个新实例。

 BigDecimal[] val = new BigDecimal[10]; // 10 for example - chosse the size you want
 Arrays.fill(val, BigDecimal.ZERO);

回答by shashi

You may pass the BigDecimalvalue this way:

您可以通过BigDecimal以下方式传递值:

BigDecimal amt = null;

amt = new BigDecimal("110000");