Reputation: 3350
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
Upvotes: 2
Views: 147
Reputation: 393791
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;
Upvotes: 6
Reputation: 3993
Arrays are not erased, and type coersion does not apply to them at all. double[]
is never the same as Double[]
, and neither of the two coerse to Number[]
.
By binding type variable like this:
class Example<T extends Number> {
private T[] arr;
}
what you actually have at runtime is:
class com.Example {
private Number[] arr;
}
That in turn means that following code:
for(T t: array) {
<...snip...>
}
is compiled in this code:
for (Number t: array) {
<...snip...>
}
As you can see, there is no information about what type of number it is, and Java does not define any operators that work on Number
classes, which evidenced by any library that did a custom Number, or even JDK itself with classes like BigInteger
and BigDecimal
.
Upvotes: 0