Restricted types in java

I can't figure out why this code won't compile ...

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);
        }
    }
}

      

Compiler error:

Error in Room.java, line 18:

Type mismatch: cannot convert from double to T

Can someone please explain why this code won't compile?

+3


source to share


4 answers


Eran is right; java.lang.Double

final

so it doesn't make sense to have a type parameter T extends Double

. The only possible type that satisfies this is Double

, so you can just remove the type parameter and just use it Double

directly (or better yet: a primitive type Double

).

The reason your code won't compile is because you are trying to use an operator +

on type objects T

.



The Java compiler is not so smart that it notices what it T

can only be Double

, so it can automatically convert (by automatic unboxing and -boxing) the value to Double

to perform the computation.

You may have come from a C ++ background and you were using C ++ templates. Java generators don't work the same way as C ++ templates; generic types in Java are not templates from which code is generated.

+5


source


There is no point in having this generic parameter having this binding:

class Average<T extends Double>

      



as Double is final and cannot be subtyped.

Therefore, you can also remove the parameter of type T and replace T with Double.

+3


source


Since I don't know what exactly your code is supposed to archive, I'm not sure if this answer is correct, but a quick fix (at least to avoid a syntax error) is to replace the line:

T sum;

      

from:

double sum;

      

That being said, your output is the incremental sum of the entire double, one after the other.

0


source


+

is an arithmetic operator for use with numbers or strings, but it cannot be used with a type Object

. If you want to use an operator +

, both operands must be of 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);
    }
  }
}

      

0


source







All Articles