Question

I want to declare a BigDecimal Array with initial value 0 like this:

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

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

Était-ce utile?

La solution

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 ;)

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

Autres conseils

You can use the predefined BigDecimal.ZERO constant:

BigDecimal[] val = { BigDecimal.ZERO,
                    BigDecimal.ZERO,
                    BigDecimal.ZERO };
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.

It's no different from if you do:

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

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.

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

You may pass the BigDecimal value this way:

BigDecimal amt = null;

amt = new BigDecimal("110000");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top