java - 扩展 Collection 时如何在 'this' 上使用 Iterable?

标签 java generics

如何解决这个错误?我只尝试了 this(Article) thissuper.iterable(),但似乎没有任何效果。只有 Article 类型才会添加到此队列中。 Java 1.7.0_03。

[javac] C:\cygwin\home\Chloe\Queue.java:26: error: incompatible types
[javac]             for (Article a: (Iterable) this) {
[javac]                             ^
[javac]   required: Article
[javac]   found:    Object

这是源代码。

public class Queue<T> extends ArrayDeque {

public int words() {
    int words;
    for (Article a: (Iterable) this) {
    }
}
}

最佳答案

队列的迭代器将返回 T Object 实例,而不是 Article。你的循环应该像这样:

public int words() {
    int words;
    for (Object a: this) {
       // do something
    }
}

或者,如果您需要文章队列,请这样声明该类:

public class Queue extends ArrayDeque<Article> {

  // this queue will store Article instances

}

关于java - 扩展 Collection 时如何在 'this' 上使用 Iterable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11980733/

相关文章:

Java HttpPost 到 php 页面

java - Apache Ignite IGFS 不使用非堆空间

java - Googleapis.com 未知主机异常

c# - EntityFramework 中使用 'where' 语句的通用查询

swift - 具有通用功能和关联类型的协议(protocol)

java - 如何使用 Class.forName 的结果创建泛型类的实例

java - libGDX 我应该在哪里使用 dispose/如何使对象成为一次性对象?

java - 如何从main调用java中的方法?

java - 我应该始终使用通配符作为函数参数的泛型类型还是仅传递一种泛型类型的实例?

java - SpringBoot : create object from generic type in generic mapper