chuey
chuey

Reputation: 1

Type casting to generic type?

public class NumberAnalyzer<T extends Number>{

public T average() {
    Double temp = 0.0;
    for (int i = 0; i < numberArray.size(); i++) {
        temp += numberArray.get(i).doubleValue();
    }
    temp /= numberArray.size();
    return (T) temp;
}

How would I type cast this so when I pass in an Integer or a Double it gives me the correct type I passed in? At the moment it's always coming back as a Double.

Is this what you meant?

public class NumberAnalyzer<T extends Number> {
private Function<Double, T> castFn;

NumberAnalyzer(Function<Double, T> castFn) {
    this.castFn = castFn;
}

private ArrayList<T> numberArray;
public T average() {
    Double temp = 0.0;
    for (int i = 0; i < numberArray.size(); i++) {
        temp += numberArray.get(i).doubleValue();
    }
    temp /= numberArray.size();
    return castFn.apply(temp);
}

This is my test class:

public static void main(String[] args) {
    ArrayList<Integer> intArrayListTest = new ArrayList<>();
    intArrayListTest.add(22);
    intArrayListTest.add(7);
    intArrayListTest.add(839);
    intArrayListTest.add(24);
    intArrayListTest.add(99);
    NumberAnalyzer<Integer> numTest = new NumberAnalyzer<>(intArrayListTest);

So the answer I'm looking for is if I pass in a int Array that has values of 8,9 and 66 it the average would be: 27

If passing a double array with the same values it would give me: 27.66

At the moment it would always return a double value even if i pass in an int.

Upvotes: 0

Views: 368

Answers (1)

Andy Turner
Andy Turner

Reputation: 140309

Casting a reference-typed variable to another reference type doesn't actually do anything to the value - it's just a way of saying to the compiler "trust me, I know more type information than you".

So, casting an Integer to a Double wouldn't make it a Double, it would just trick the compiler into believing the type, leading to subsequent problems when it tries to use that Integer as a Double.

You aren't looking to cast here, you are looking to convert.

You would need to pass in a Function<Double, T> or a DoubleFunction<T>, either as a parameter to the method or the constructor.

public T average(Function<Double, T> castFn) {
   // ...
   return castFn.apply(temp);
}

or

public class NumberAnalyzer<T extends Number>{
  private Function<Double, T> castFn;

  NumberAnalyzer(Function<Double, T> castFn) { this.castFn = castFn; }

  public T average() {
    // ...
   return castFn.apply(temp);
}

Upvotes: 1

Related Questions