How can I increment BigDecimal in java through for loop? This is the codes that I am currently running and I don't understand why it won't increment the BigDecimal instances
package app;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class Test {
private List<BigDecimal> ticketQuantity = new ArrayList<>();
List<String> someNumber = new ArrayList<>();
public Test() {
ticketQuantity.add(new BigDecimal(0));
ticketQuantity.add(new BigDecimal(0));
ticketQuantity.add(new BigDecimal(0));
ticketQuantity.add(new BigDecimal(0));
someNumber.add("10");
someNumber.add("10");
someNumber.add("10");
someNumber.add("10");
System.out.println(ticketQuantity);
int i = 0;
for (BigDecimal x : ticketQuantity) {
x.add(new BigDecimal(someNumber.get(i)));
i++;
}
System.out.println(ticketQuantity);
}
public static void main(String[] args) {
new Test();
}
}
What did I miss? I am hoping that someNumber would equals to [10, 10, 10, 10]
but then [0, 0, 0, 0]
is printed :(
BigDecimal
represents:
Immutable, arbitrary-precision signed decimal numbers
The immutability means you can't modify an instance. The add
method will return a new BigDecimal
. If you want to change the value in the list, you will have to go through the loop by index and call List.set
with the index to replace and the result of BigDecimal.add
:
for (int i = 0; i < ticketQuantity.size(); i++) {
ticketQuantity.set(i, ticketQuantity.get(i).add(someNumber.get(i)));
}
As explained in other answer, add()
method will return a new BigDecimal
and wouldn't modify the original instance due to BigDecimal
being immutable so you need to do as below,
int i = 0;
for (BigDecimal x : ticketQuantity) {
x = x.add(new BigDecimal(someNumber.get(i)));
ticketQuantity.set(i, x);
i++;
}
As others have stated BigDecimal is an immutable class. The method BigDecimal#add
actually returns another instance of BigDecimal
, doesn't update the operand BigDecimal
object. To achieve your object, you can try the following way:
public class Test {
private List<BigDecimal> ticketQuantity = new ArrayList<>();
List<String> someNumber = new ArrayList<>();
public Test() {
someNumber.add("10");
someNumber.add("10");
someNumber.add("10");
someNumber.add("10");
System.out.println(ticketQuantity);
for (String x : someNumber) {
ticketQuantity.add(new BigDecimal(x));
}
System.out.println(ticketQuantity);
}
public static void main(String[] args) {
new Test();
}
}
add() method adds new elements at the end of list. I think you are trying to overwrite on first four values you 've added previously. so use set(int index,E element);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.