2

私は、さまざまな数の引数を取る、1つのメソッドを使用して数学演算のインターフェースを作成しました。

public interface MathOperation {
    public <T extends Number> T calculate(T... args);
}

このクラスの単純な実装もありますが、これは機能しません。

private class Sum implements MathOperation {
    @Override
    public <T extends Number> T calculate(T... args) {
        return args[0] + args[1];
    }
}

問題は:

bad operand types for binary operator '+'
  first type:  T
  second type: T
  where T is a type-variable:
    T extends Number declared in method <T>calculate(T...)

私が達成しようとしているのは、たとえば 2 つの Double を取り、Double を返す単純なクラスです。

これを達成する可能性はありますか?

4

3 に答える 3

4

+の型には適用できませんextend Numbernew Integer(5) + new Integer(5)オートボクシングのために動作します。args のランタイム タイプを確認し、それに応じて操作を行う必要があります。

次の行に何か:

private class Sum implements MathOperation {
    @Override
    public <T extends Number> T calculate(Class<T> clazz, T... args) {
         if (clazz.equals(Integer.class))
         {
             return Integer.class.cast(args[0]) + Integer.class.cast(args[1]);
         } else (....) 
    }
}
于 2013-02-18T23:17:53.940 に答える
0

他の回答に示されているように、ランタイムタイプをテストできます。または、別の設計を試すこともできます。ファクトリとして機能する抽象クラスを作成します。

interface MathContext<T extends Number> {

    ...

    T valueOf(double d);
    T valueOf(int i);
    T add (T... args);
}

そして、使用したいタイプの具象クラス:

DoubleContext implements MathContext<Double> {

    ...

    Double valueOf(int i) {
        return i;
    }

    Double valueOf(double d) {
        return d;
    }

    Double add(Double... args) {
        Double res = 0;
        for (Double arg: args)  {
            res += arg;
        }
        return res;
    }

}

これで、そのクラスを使用してMathOperationを実装できます。しかし、それはもう本当に必要ではありません。

于 2013-02-18T23:28:53.830 に答える