【问题标题】:Generic class implementing Iterable实现 Iterable 的通用类
【发布时间】:2011-03-18 20:02:59
【问题描述】:

我想要一个泛型类,它实现类型 T 的 Iterable(我们称之为 ImplIterable),它在某个类(不是泛型类类型)上实现 Iterable 接口;例如:

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 正确实现了可迭代,为什么我不能迭代它。我是不是做错了什么/是否有针对此类问题的解决方法?

【问题讨论】:

  • 它给出了什么错误?
  • incompatible types found : java.lang.Object required: java.lang.String

标签: java iterable


【解决方案1】:

当您使用没有泛型参数的泛型类时,该类中的所有泛型都将被禁用。

由于ImplIterable 是泛型的,并且您将它用作非泛型类,它内部的泛型参数消失了,它变成了Objects 的Iterable(非泛型)。

【讨论】:

猜你喜欢
  • 2019-10-27
  • 1970-01-01
  • 2020-01-24
  • 2019-06-23
  • 2014-12-19
  • 1970-01-01
  • 2011-08-28
  • 2015-12-10
相关资源
最近更新 更多