2 つの問題があります。1 つ目は、高速にする必要がある場合は、プリミティブを直接使用する必要があり、これらはジェネリックのパラメーターとしてサポートされていません。これは事実上、3 つのバージョンをPoint
個別に維持する必要があることを意味します。
ジェネリクスを使用したい場合は、対応するクラス ( などInteger
) を使用できますが、まだ 1 つの問題があります。それらのスーパー タイプにはメソッドNumber
がありません(演算子やは言うまでもなく)。add
+
+=
したがって、私が知っている唯一の方法は、add
メソッドをサポートする独自の数値クラス階層を実装することです。
abstract class Numeric<T extends Number> {
public abstract T getValue();
public abstract Numeric<T> add(Numeric<T> other);
@Override
public String toString() {
return getValue().toString();
}
}
class MyInt extends Numeric<Integer> {
public final Integer value;
public MyInt(Integer _value) {
super();
this.value = _value;
}
@Override
public Integer getValue() {
return this.value;
}
@Override
public Numeric<Integer> add(Numeric<Integer> other) {
return new MyInt(this.value + other.getValue());
}
}
class MyDouble extends Numeric<Double> {
public final double value;
public MyDouble(Double _value) {
super();
this.value = _value;
}
@Override
public Double getValue() {
return this.value;
}
@Override
public Numeric<Double> add(Numeric<Double> other) {
return new MyDouble(this.value + other.getValue());
}
}
これに基づいて、少なくとも一般的なポイントを実装できます。
class NumericPoint<T extends Number> {
public final Numeric<T> x;
public final Numeric<T> y;
public NumericPoint(Numeric<T> _x, Numeric<T> _y) {
super();
this.x = _x;
this.y = _y;
}
public NumericPoint<T> add(NumericPoint<T> other) {
return new NumericPoint<T>(this.x.add(other.x), this.y.add(other.y));
}
@Override
public String toString() {
return "(" + this.x + "/" + this.y + ")";
}
}
で使用する
NumericPoint<Integer> ip1 =
new NumericPoint<Integer>(new MyInt(1), new MyInt(2));
NumericPoint<Integer> ip2 =
new NumericPoint<Integer>(new MyInt(3), new MyInt(4));
NumericPoint<Integer> ip = ip1.add(ip2);
System.out.println(ip);
NumericPoint<Double> dp1 =
new NumericPoint<Double>(new MyDouble(1.1), new MyDouble(2.1));
NumericPoint<Double> dp2 =
new NumericPoint<Double>(new MyDouble(3.1), new MyDouble(4.1));
NumericPoint<Double> dp = dp1.add(dp2);
System.out.println(dp);
私はあなたの例を修正しました: The numerics and the points are immutable . 例のように実装されBigDecimal
ています。したがって、add
メソッドはジェネリック クラスに属し、新しいインスタンスを返します。