I want to do math with a collection of Objects that are type Number
. In this example I just want to sum them. What I could come up with currently is to just do a switch statement and then cast to a BigDecimal, as that is the largest value that I would be working with. This is working correctly right now and sums to 20.
This seems pretty involved and a large amount of work to do something pretty simple. Is there a better way to do this?
import java.math.BigDecimal;
public class NumberArray {
public static BigDecimal sum(Number[] nums) {
BigDecimal summation = new BigDecimal(0);
for (Number n : nums) {
switch (n.getClass().getName()) {
case "java.lang.Integer":
summation = summation.add(new BigDecimal((Integer) n));
break;
case "java.lang.Double":
summation = summation.add(new BigDecimal((Double) n));
break;
case "java.lang.Long":
summation = summation.add(new BigDecimal((Long) n));
break;
case "java.lang.Float":
summation = summation.add(new BigDecimal((Float) n));
break;
case "java.math.BigDecimal":
summation = summation.add((BigDecimal)n);
break;
default:
throw new IllegalArgumentException("Unsupported num: " +n.getClass().getName());
}
}
return summation;
}
public static void main(String[] args) {
Number[] nums = { 1, 1, 2, 2, 1L, 1f, new BigDecimal(10), 2.0 };
System.out.println(sum(nums));
}
}