开发者

Java iteration problem

"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.O开发者_如何转开发bject
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?


Catalog needs to implement Iterable<Item> and its iterator() method needs to return Iterator<Item>.


public class Catalog implements Iterable<Item>{
public Iterator<Item> iterator(){
  return itemList.iterator();
}


Make sure it implements Iterable<Item>, not just Iterable.


It needs to implement Iterable<Item>.


You need to specify a type parameter for the iterator

public Iterator<Item> iterator() {
    Iterator<Item> itr = itemList.iterator();
    return itr;
}   

and when Catalag implements Iterable make sure it implements Iterable<Item>.


It should implement:

 Iterable<Item>

(note the parameter)


Try something like:

for(Item item : catalog.itemList) {
    item.getProperty();
    // ... and so on.
}

as your Catalog class is not iterable, but it's itemList List is.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜