3

Javaでジェネリッククラスを作ろうとしています。いくつかのガイドを読んで、それを宣言する方法と、その関数を呼び出す方法も見つけました。

私のクラスはポイントであり、メソッドがなければ次のようになります。

class Pnt<type>{
  protected type x, y;
  protected int col;
}

今、メソッドを作ろうとしてaddいますが、できません。

私が試したのは:

  void add(type x_, type y_){
    x += x_;
    y += y_;
  }

IDEは、変数+=が未定義であると私に怒鳴っていtypeます...

Java では C++ のように新しい演算子を定義できないことを知っているので、2 つのtype変数を追加する別の方法を求めています!

PS 使用するすべてのタイプはdoubles、floats、integers です。そのため、単純な中毒を作成しようとしています。

4

2 に答える 2

1

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メソッドはジェネリック クラスに属し、新しいインスタンスを返します。

于 2013-06-03T19:05:56.790 に答える