1

私は自分のプロジェクトに と呼ばれる機能的インターフェースを定義しましたFunctioncall次のように、メソッドは 1 つだけです。

    public interface Function {
       public void call();
    }

そして、私の Field オブジェクトには、これがあります:

    public class Field {
      private Square[][] matrix; //Square is dispensable.
      public Field(int rows, int cols) {
        matrix = new Square[rows][cols];
        for(int i = 0; i < rows; i++){
          for(int j = 0; j < cols; j++){
            this.matrix = new Square(i * Square.NORMAL_WIDTH, j * Square.NORMAL_HEIGHT);
          }
        }
      }
    }

これは正常に動作し、JavaScript に似ていますが、注意を向けているオブジェクトを渡すことができません。しかし、私はこの方法を開発したいと考えています:

    public void each(Function f){
      int rows = matrix.length;
      for(int i = 0; i < rows; i++){
        int cols = matrix[i].length;
        for(int j = 0; j < cols; j++){
          f.call();
        }
      }
    }

特定のコード (この場合は Function の実装) をマトリックスのすべての要素にアタッチします。そうすれば、そのプロパティにアクセスできます。しかし、行列のすべてのオブジェクトは正方形です。どうすればアクセスできますか? 私はそれを関数に渡すことができました、

    //making an small alteration to the parameter.
    public interface Function {
       public void call(Square square);
    }

    public void each(Function f){
      int rows = matrix.length;
      for(int i = 0; i < rows; i++){
        int cols = matrix[i].length;
        for(int j = 0; j < cols; j++){
          f.call(matrix[i][j]);
        }
      }
    }

それでも、私はSquareタイプにとらわれます。ジェネリック型を使用できますか?

4

2 に答える 2

2

はい、ジェネリックにする必要があります。

最も単純なケース:

public interface Function<T> {
    public void call(T arg);
}

public void each(Function<Square> f) { ... }

次のように宣言することをお勧めeach()します。

public void each(Function<? super Square> f) { ... }

Function<Square>だけでなくFunction、そのスーパータイプの にも適用できます。

Function<Object> PRINT = new Function<Object>() {
    public void call(Object arg) {
        System.out.println(arg);
    }
}
于 2013-06-21T17:57:49.743 に答える
0

それ以外の

private Square[][] matrix;

使用する

private Function[][] matrix;

コードは Square に関連付けられていません。もちろん、最終的には具体的なクラスに結び付けられますが、コードはあまり結合されていません。(そして、ジェネリックがそこで役立つかどうかはわかりません。朝が早すぎて、もっと一生懸命考えることができないからです:-)

于 2013-06-21T17:58:41.583 に答える