2

いくつかのクラス(ジェネリッククラスタイプではない)にIterableインターフェースを実装するタイプTのIterable(ImplIterableと呼びましょう)を実装するジェネリッククラスが必要です。例えば:

public class ImplIterable <T> implements Iterable<A> {
   private A[] tab;

   public Iterator<A> iterator() {
      return new ImplIterator();
   }

   // doesn't work - but compiles correctly.
   private class ImplIterator implements Iterator<A> {
      public boolean hasNext() { return true; }

      public A next() { return null; }

      public void remove() {}
   }
}

A はあるクラスです。さて、このコードはコンパイルされません:

ImplIterable iable = new ImplIterable();
for (A a : iable) {
   a.aStuff();
}

しかし、これは:

Iterable<A> = new ImplIterable();
for (A a : iable) {
   a.aStuff();
}

後者がコンパイルされない理由と、反復可能を適切に実装している場合に ImplIterable を反復処理できない理由がわかりません。私は何か間違ったことをしていますか/この種の問題に対する回避策はありますか?

4

1 に答える 1

3

ジェネリック パラメーターを指定せずにジェネリック クラスを使用すると、そのクラスのすべてのジェネリックが無効になります。

はジェネリックであり、それImplIterableを非ジェネリック クラスとして使用しているため、その中のジェネリック パラメータは消失し、 s のIterable(非ジェネリック) になりObjectます。

于 2011-03-18T20:10:55.443 に答える