James T. James T. - 1 year ago 93
Java Question

How do I call a method on each object inside of an array?

Gist of my full code, 31 lines

I'm trying to convert doubles -> BigDecimal then call setScale method on each of the BigDecimal objects stored inside of an array.

// convert double variables to BigDecimal inside of new BigDecimal array
BigDecimal[] ret = new BigDecimal[]{
new BigDecimal(area),
new BigDecimal(theta),
new BigDecimal(x),
new BigDecimal(y)
// setScale on each object
for (BigDecimal val: ret) {
val.setScale(2, RoundingMode.FLOOR);

But when I print this out, it's clear the setScale function was not called on any of the objects when I print each out later.

Are the objects in the array not being mutated or saved in the 2nd for loop?

Update & Adjustment with Answer-Advice:

Based on Hovercraft's answer I rewrote the last bit of my code here to:

double[] vals = new double[]{area, theta, x, y};
BigDecimal[] ret = new BigDecimal[vals.length];
for (int i = 0; i < vals.length; i++) {
ret[i] = new BigDecimal(vals[i]).setScale(2, RoundingMode.FLOOR);

Which does exactly what I wanted.

Answer Source

BigDecimal like String is immutable, and so just calling setScale(...) on the BigDecimal object will have no effect on the same object. For the scale to be set, you have to re-assign the result to the BigDecimal variable. For this purpose, I would not use a for-each loop, but rather a for loop:

for (int i = 0; i < ret.length; i++) {
   ret[i] = ret[i].setScale(2, RoundingMode.FLOOR);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download