Search code examples
javagenericsautoboxing

Autoboxing/Auto-unboxing is not working for bounded Type parameter


Here is what I am trying to do :

class MyNumbers<T extends Number>{

    private T[] array;

    MyNumbers(T[] array){
            this.array = array;
        }
    public void setArray(T[] array){
        this.array = array;
    }
    public T[] getArray(){

            return this.array;
        }


    public double avarage(){

            double avg =0.0;
            double sum =0.0;
            for(T t: array){
                    sum += t.doubleValue(); // working
                    sum = sum+ t; // not working

                }
                return sum/array.length;            }
}

As per autoboxing and unboxing rule sum = sum+ t; should work. but not working as T already extending with Number class .

Here is what I trying with following type:

public class BoundedTypeParam{

    public static void main(String [] args){

        Integer[] ints = {1,2,3,4,5,6};
        MyNumbers<Integer> stats4Ints = new MyNumbers<>(ints);

        System.out.println("Avg is same : "+ stats4Ints.avarage());

    }

}

Any rule/concept that I am missing.

PS. I am aware with reifiable type, erasure


Solution

  • This has nothing to do with generics. It wouldn't work if you replaced T with Number.

    There is no unboxing conversion from Number type to some primitive type, so Number cannot be an operand of a numeric operator.

    The following code will fail to pass compilation for the exact same reason as your code - The operator += is undefined for the argument type(s) double, Number.

    Number n = 5;
    double sum = 0.0;
    sum += n;