Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.Number doesn't implement "+" or any other operators?

I'm creating a class which is supposed to be able to be used with an array of any type of number (float, int, etc), so here is one method I have:

// T extends Number
public synchronized T[] average() {
    Number[] ret = new Number[queue[0].length];
    for (int i = 0; i < ret.length; ++i) {
        for (int j = 0; j < size; ++j) {
            ret[i] += queue[j][i]; // WTF ERROR?!
        }
        ret[i] /= size; // WTF ERROR?!
    }
    return (T[])ret;
}

Except this won't compile because "Number" doesn't implement the "+=" or "/=" operators. Event worse, java's Number class doesn't implement even the most basic operators like "+" or "-"! How can I make a method which returns the average of an array of Numbers if java won't let me compile it because it thinks that numbers can't be added?!?!

like image 404
Dasmowenator Avatar asked Jan 22 '12 00:01

Dasmowenator


2 Answers

You're misunderstanding the way numbers work in Java. The Number class is the superclass of numeric wrapper classes (Integer, Float, etc.) useful for representing primitive types (int, float, etc.) as objects, but it does not work with the usual arithmetic operators.

If you intend to use the arithmetic operators, then use primitive types. If you need to build a "generic" method that works for all numeric data types, you have no choice but to build several overloaded versions of the same method, one for each data type, for example:

public  float[] average(float[][]  queue) {...}
public double[] average(double[][] queue) {...}

Also be aware that code like this appears to work for wrapper types:

Integer i = 0;
i += 1;
System.out.println(i);

... But under the hood, Java is automatically boxing and unboxing the Integer, since the += operator only works for primitive types. It works because we're explicitly indicating that the number is an Integer, but it won't work for a Number, since Java needs to know exactly what type of number it's dealing with for performing the boxing/unboxing.

like image 78
Óscar López Avatar answered Sep 22 '22 08:09

Óscar López


You need to convert your numbers to primitive types, and then the arithmetic operators will work. You will notice that Number does have doubleValue, intValue, etc....

or alternatively, you can convert to BigDecimal, and use the arithmetic methods defined on that class (not +,-, etc, but add, multiply, etc....). This method will be more accurate (if you need the best accuracy, use BigDecimal) since floats and doubles only represent a discrete set of numeric values. Keep in mind that BigDecimals are immutable, so you always need to assign the result of an operation to a reference.

like image 43
hvgotcodes Avatar answered Sep 26 '22 08:09

hvgotcodes