2012-07-09 103 views
0

以下是我的学习目标。我已经开始了,但我真的不知道该从哪里开始执行主程序。我将不胜感激任何帮助!将迭代器添加到集合中

目的:

  • 通过创建一个私有的内部类添加一个Iterator对象的采集卡
  • 迭代器被添加到收藏。
  • 您可以使用任何适当的内部类类型
  • 枚举器和迭代器使用大量数据来确定集合何时更改。
  • 实现正确的方法,接口并为与Java API一致的类扩展适当的类。

    public class CardCollection { 
    
    private ArrayList<Card> cards; 
    private ArrayList<Note> notes; 
    
    public CardCollection() { //constructor initializes the two arraylists 
        cards = new ArrayList<Card>(); 
        notes = new ArrayList<Note>(); 
    } 
    
    private class Card implements Iterable<Card> { //create the inner class 
    
        public Iterator<Card> iterator() { //create the Iterator for Card 
         return cards.iterator(); 
        } 
    } 
    
    private class Note implements Iterable<Note> { //create the inner class 
    
        public Iterator<Note> iterator() { //create the Iterator for Note 
         return notes.iterator(); 
        } 
    
    } 
    
    public Card cards() { 
        return new Card(); 
    } 
    
    public Note notes() { 
        return new Note(); 
    } 
    
    public void add(Card card) { 
        cards.add(card); 
    } 
    
    public void add(Note note) { 
        notes.add(note); 
    } 
    
    } 
    
+3

这是非常,非常不寻常 - 可能不是你的意思 - 有一类'Foo'实现的Iterable''。你应该确保你跟踪哪些东西应该是多个'Foo',哪个应该是一个'Foo'。 – 2012-07-09 20:36:02

回答

2

你有两个概念,我认为你可能混在一起。如果可迭代某些内部元素,则该对象为Iterable。

所以,如果我有一个物品在其中的购物车,我可以迭代我的杂货。

public class ShoppingCart implements Iterable<GroceryItem> 
{ 
    public Iterator<GroceryItem> iterator() 
    { 
     // return an iterator 
    } 
} 

所以为了使用这个功能,我需要提供一个Iterator。在你的代码示例中,你正在重用ArrayList中的迭代器。从你的练习描述中,我相信你需要自己实现一个。例如:

public class GroceryIterator implements Iterator<GroceryItem> 
{ 
    private GroceryItem[] items; 
    private int currentElement = 0; 

    public GroceryIterator(GroceryItem[] items) 
    { 
    this.items = items; 
    } 

    public GroceryItem next() // implement this 
    public void remove() // implement this 
    public boolean hasNext() // implement this 
} 

所以我给你一个提示构造函数/成员变量。在你创建这个类后,你的Iterable类(我的ShoppingCart)将返回我的新迭代器。

该分配建议为您的自定义迭代器使用私有内部类。

好运

1
  • 可迭代对象通常是集合。 CardCollection比Card更适合
  • 公共方法cards()和notes()返回类型Card和Note,它们是私有的。我认为这些意图是公开的。
  • 我觉得方法cards()和notes()是为了返回迭代器。