Reputation: 1970
I am unable to understand why this code is not compiling...
public class Room {
public static void main(String[] args) {
Double[] ar = {1.1,2.23,3.56,4.23,5.90,6.88,7.99,8.09,9.88,10.99};
Average<Double> tt = new Average<>(ar);
tt.summ();
}
}
class Average<T extends Double> {
T[] arr;
T sum;
Average(T[] num) {
arr = num;
}
void summ() {
for (T i : arr) {
sum = sum + i;//Shows incompatible types
System.out.println(sum);
}
}
}
The compiler error states:
Error on Room.java, line 18:
Type mismatch: cannot convert from double to T
Can somebody please explain why this code is not compiling??
Upvotes: 3
Views: 175
Reputation: 1
+
is arithmetic operator to use with numbers or strings, but it cant be used with Object
type. If you want to use +
operator both operand should have the same type.
class Average<T extends Double> {
T[] arr;
double sum = 0;
Average(T[] num) {
arr = num;
}
void summ() {
for (T i : arr) {
sum += (Double)i;//Shows incompatible types
System.out.println(sum);
}
}
}
Upvotes: 0
Reputation: 206766
Eran is right; java.lang.Double
is final
, so it makes no sense to have a type parameter T extends Double
. The only possible type that satiesfies this is Double
itself, so you can just as well remove the type parameter and just use Double
directly (or better yet: the primitive type double
).
The reason why your code doesn't compile is because you are trying to use the +
operator on objects of type T
.
The Java compiler is not so smart that it notices that T
can only be Double
, so that it automatically can convert (by auto-unboxing and -boxing) the value to a double
to do the calculation.
Maybe you come from a C++ background and you've used C++ templates. Java generics do not work in the same way as C++ templates; generic types in Java are not templates from which code is generated.
Upvotes: 5
Reputation: 352
Since I don't know what exactly your code should archive, I am not sure about the correctness of this answer, but a quick fix (at least to avoid syntax error) is to substitute the line:
T sum;
with:
double sum;
With this, your output is the incremental sum of all the double, one by one.
Upvotes: 0
Reputation: 393771
There is no point in this generic type parameter having this bound :
class Average<T extends Double>
since Double is final and can have no sub-types.
Therefore you might as well remove the generic type parameter T and replace T with Double everywhere.
Upvotes: 3