Java迭代问题
“Catalog”是一个存储“Item”对象集合的类。为此,我选择使用 List 集合。所以它看起来像:
public class Catalog {
List<Item> itemList;
主类必须能够使用 for 循环访问 Item 元素,该 for 循环将 Catalog 对象视为集合本身。假设有一个名为“catalog:”的 Catalog 对象
for (Item items : catalog) {
//various operations involving item
}
问题:我收到不兼容类型错误。
found: java.lang.Object
requird: Item
我的 Catalog 类实现了 Iterable,并且有一个方法 iterator(),它返回 List 的迭代器:
public Iterator iterator() {
Iterator itr = itemList.iterator();
return itr;
}
那么我做错了什么?
"Catalog" is a class that stores a collection of "Item" objects. I have chosen to use a List collection for this purpose. So it looks like:
public class Catalog {
List<Item> itemList;
The main class must be able to access the Item elements with a for loop that treats a Catalog object like a collection itself. Assume a Catalog object named "catalog:"
for (Item items : catalog) {
//various operations involving item
}
Problem: I get the incompatible types error.
found: java.lang.Object
requird: Item
My Catalog class implements Iterable and has a method iterator() that returns an iterator for the List:
public Iterator iterator() {
Iterator itr = itemList.iterator();
return itr;
}
So what am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Catalog
需要实现Iterable
并且它的iterator()
方法需要返回Iterator
。Catalog
needs to implementIterable<Item>
and itsiterator()
method needs to returnIterator<Item>
.确保它实现了
Iterable
,而不仅仅是Iterable
。Make sure it implements
Iterable<Item>
, not justIterable
.它需要实现
Iterable
。It needs to implement
Iterable<Item>
.您需要为迭代器指定类型参数
,并且当
Catalag 实现 Iterable
时,请确保它实现 Iterable
。You need to specify a type parameter for the iterator
and when
Catalag implements Iterable
make sure itimplements Iterable<Item>
.它应该实现:(
注意参数)
It should implement:
(note the parameter)
尝试如下操作:
因为您的
Catalog
类不可迭代,但它的 itemList List 是可迭代的。Try something like:
as your
Catalog
class is not iterable, but it's itemList List is.