域名没备案如何建设网站,成华区微信网站建设推广,剁椒怎么做制作方法,怎么查开发商剩余房源有许多方法可以把对象堆起来成为一个集合#xff08;Collection#xff09;#xff0c;比如放入数组、堆栈或散列表中。若用户直接从这些数据结构中取出对象#xff0c;则需要知道具体是存在什么数据结构中#xff08;如栈就用peek#xff0c;数组[]#xff09;。迭代器…有许多方法可以把对象堆起来成为一个集合Collection比如放入数组、堆栈或散列表中。若用户直接从这些数据结构中取出对象则需要知道具体是存在什么数据结构中如栈就用peek数组[]。迭代器能够让客户遍历你的对象而又无法窥视你存储对象的方式。
对象村餐厅和煎饼屋合并了它们有着不同的菜单列表但菜单项基础都是一样的。
class MenuItem
{
private:string name;string description;bool vegetarian;double price;public:MenuItem(string name, string description, bool vegetarian, double price){this-name name;this-description description;this-vegetarian vegetarian;this-price price;}string getName(){return name;}string getDescription(){return description;}bool isVegetarian(){return vegetarian;}double getpPrice(){return price;}
};
下面就写Java代码了改成C一时半会还是做不过来。
public class PancakeHouseMenu
{ArrayList menuItems;public PancakeHouseMenu(){menuItems new ArrayList();addItem(KBs Pancake Breakfast, Pancakes with scrambled eggs, and toast, true, 2.99);}public void addItem(String name, String description, boolean vegetarian, double price){MenuItem menuItem new MenuItem(name, description, vegetarian, price);menuItems.add(menuItem);}public ArrayList getMenuItems(){return menuItems;}
};/ ********************************************************/
public class DinerMenu
{static final int MAX_ITEMS 6;int numberOfItems 0;MenuItem[] menuItems;public DinerMenu(){menuItems new MenuItem[MAX_ITEMS];addItem(Vegetarian BLT, Fakin Bacon, true, 2.99);}public void addItem(String name, String description, boolean vegetarian, double price){MenuItem menuItem new MenuItem(name, description, vegetarian, price);if (numberOfItems MAX_ITEMS){System.err.println(Sorry, menu is full! Cant add item to menu);}else{menuItems[numberOfItems] menuItem;}}public MenuItem[] getMenuItems(){return menuItems;}
};
这两种不同的菜单表现方式会使得女招待需要知道菜单的实现细节才能对菜单进行遍历。
PancakeHouseMenu pancakeHouseMenu new PancakeHouseMenu();
ArrayList breakfastItems pancakeHouseMenu.getMenuItems();for breakfastItems.size()
MenuItem menuItem (MenuItem)breakfastItems.get(i);/ ******************************************************************* /
DinerMenu dinerMenu new DinerMenu();
MenuItem[] lunchItems DinerMenu.getMenuItems();for lunchItems.size()
MenuItem menuItem lunchItems[i];
如果还有第三家餐厅以不同的实现出现我们就需要有三个循环。
因此我们需要创建一个对象迭代器封装“遍历集合内的每个对象的过程”。
Iterator iter breakfastItems.createIterator();while (iter.hasNext())
{MenuItem menuItem (MenuItem)iter.next();
} 当我们拥有迭代器接口后我们就可以为各种对象集合实现迭代器