简体   繁体   English

类型转换为泛型类型?

[英]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?我将如何输入这个,所以当我传入 Integer 或 Double 时,它会给我传入的正确类型? At the moment it's always coming back as a Double.目前,它总是以 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:这是我的测试 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所以我正在寻找的答案是,如果我传入一个值为 8,9 和 66 的 int 数组,则平均值为:27

If passing a double array with the same values it would give me: 27.66如果传递具有相同值的双精度数组,它将给我:27.66

At the moment it would always return a double value even if i pass in an int.目前,即使我传入一个 int,它也总是会返回一个 double 值。

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 .因此,将Integer转换为Double不会使其成为Double ,它只会诱使编译器相信该类型,从而在尝试将Integer用作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.您需要传入Function<Double, T>DoubleFunction<T> ,作为方法或构造函数的参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM