Home > Java > javaTutorial > Detailed explanation of the use of iterators in Java

Detailed explanation of the use of iterators in Java

黄舟
Release: 2017-09-23 10:13:24
Original
1315 people have browsed it

This article mainly introduces relevant information on the detailed use of iterators in java. I hope this article can help everyone. Friends in need can refer to

The use of iterators in java Detailed explanation of method

Preface:

The iterator pattern encapsulates a collection, mainly to provide users with a way to traverse its internal elements. The iterator pattern has two advantages: ① It provides users with a way to traverse without exposing its internal implementation details; ② It assigns the responsibility of traveling between elements to iterators instead of aggregate objects, realizing the integration between users and aggregate objects. decoupling between.

The iterator mode mainly manages an aggregate object through the Iterator interface. When using it, the user only needs to get an Iterator type object to complete the traversal of the aggregate object. The aggregate objects here generally refer to ArrayList, LinkedList and the underlying implementation is an array, etc., which have a set of objects with the same or similar characteristics. The traversal of aggregate objects through the iterator mode is mainly performed through the next() and hasNext() methods of the Iterator interface. The next() method here will return the element value of the current traversal point, and the hasNext() method represents the current traversal point. There are no elements after that. There is also a remove() method in the Iterator interface, which will remove the element at the current traversal point. This method does not need to be used under normal circumstances. This method can be called in some special cases. If the traversal of the current aggregate object does not support this operation, an UnSupportedOperationException can be thrown in this method.

Here we use the following example to illustrate the iterator pattern. There are currently two sets of menus for two restaurants. One set of menus is implemented using an array, while the other set of menus is implemented using an ArrayList. Now due to the merger of the two restaurants, the two sets of menus need to be integrated. Since the chefs on both sides have become accustomed to their respective menu assembly methods, they both hope to continue to maintain their own menu styles. However, for waiters, when providing menus to customers, they must handle them in two different ways according to two sets of menus, which will inevitably increase the difficulty of the waiters' work. Moreover, if new restaurants are merged in later, such as If the menu type used is HashMap, then the waiter will maintain this set of menus, which is not conducive to expansion. According to the needs of the waiter, what he needs is a menu list. If it is oriented to different menu categories, it will inevitably increase the difficulty of his work, and the methods provided in different menu categories are not necessarily what the waiter needs. Therefore, according to the needs of the waiter, a menu specification needs to be formulated so that the waiter can traverse it in the same way. The iterator pattern can be used here. The waiter only needs to traverse the iterator interface, and the menu owned by each chef only needs to implement the iterator, and they can still maintain their menu items in their own way. This achieves the decoupling of different menus and waiters. Below is the specific code to solve this problem using the iterator pattern.

Menu interface (mainly contains methods for creating iterators):


public interface Menu<T> {
  Iterator<T> createIterator();
}
Copy after login

Menu items:


public class MenuItem {
  private String name;
  private String description;
  private boolean vegetarian;
  private double price;

  public MenuItem(String name, String description, boolean vegetarian, double price) {
    this.name = name;
    this.description = description;
    this.vegetarian = vegetarian;
    this.price = price;
  }

  public String getName() {
    return name;
  }

  public String getDescription() {
    return description;
  }

  public boolean isVegetarian() {
    return vegetarian;
  }

  public double getPrice() {
    return price;
  }
}
Copy after login

Menu class (how to assemble menu items):


public class DinerMenu implements Menu<MenuItem> {
  private static final int MAX_ITEMS = 6;
  private int numberOfItems = 0;
  private MenuItem[] menuItems;

  public DinerMenu() {
    menuItems = new MenuItem[MAX_ITEMS];
    addItem("Vegetarian BLT", "(Fakin&#39;) Bacon with lettuce & tomato on whole wheat", true, 2.99);
    addItem("BLT", "Bacon with lettuce & tomato on whole wheat", false, 2.99);
    addItem("Soup of the day", "Soup of the day, with a side of potato salad", false, 3.29);
    addItem("Hotdog", "A hot dog, with saurkraut, relish, onions, topped with cheese", false, 3.05);
  }

  public void addItem(String name, String description, boolean vegetarian, double price) {
    MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
    if (numberOfItems >= MAX_ITEMS) {
      System.out.println("Sorry, menu is full, Can&#39;t add item to menu");
    } else {
      menuItems[numberOfItems] = menuItem;
      numberOfItems++;
    }
  }

  @Deprecated
  public MenuItem[] getMenuItems() {
    return menuItems;
  }

  public Iterator<MenuItem> createIterator() {
    return new DinerMenuIterator(menuItems);
  }
}
public class PancakeHouseMenu implements Menu<MenuItem> {
  private ArrayList<MenuItem> menuItems;

  public PancakeHouseMenu() {
    menuItems = new ArrayList<>();
    addItem("K&B&#39;s Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true, 2.99);
    addItem("Regular Pancake Breakfast", "Pancakes with fried eggs, sausage", false, 2.99);
    addItem("Blueberry Pancakes", "Pancakes made with fresh blueberries", true, 3.49);
    addItem("Waffles", "Waffles, with your choice of blueberries or strawberries", true, 3.49);
  }

  public void addItem(String name, String description, boolean vegetarian, double price) {
    MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
    menuItems.add(menuItem);
  }

  @Deprecated
  public ArrayList<MenuItem> getMenuItems() {
    return menuItems;
  }

  public Iterator<MenuItem> createIterator() {
    return menuItems.iterator();
  }
}
Copy after login

Iterator interface:


public interface Iterator<T> {
  boolean hasNext();
  T next();
}
Copy after login

Iteration Server class:


public class DinerMenuIterator implements Iterator<MenuItem> {
  private MenuItem[] items;
  private int position = 0;

  public DinerMenuIterator(MenuItem[] items) {
    this.items = items;
  }

  @Override
  public boolean hasNext() {
    return position < items.length && items[position] != null;
  }

  @Override
  public MenuItem next() {
    return items[position++];
  }

  @Override
  public void remove() {
    if (position <= 0) {
      throw new IllegalStateException("You can&#39;t remove an item until you&#39;ve done at least one next()");
    }

    if (items[position - 1] != null) {
      for (int i = position - 1; i < items.length - 1; i++) {
        items[i] = items[i + 1];
      }
      items[items.length - 1] = null;
    }
  }
}
public class PancakeHouseIterator implements Iterator<MenuItem> {
  private ArrayList<MenuItem> items;
  private int position = 0;

  public PancakeHouseIterator(ArrayList<MenuItem> items) {
    this.items = items;
  }

  @Override
  public boolean hasNext() {
    return position < items.size();
  }

  @Override
  public MenuItem next() {
    return items.get(position++);
  }
}
Copy after login

Waiter class:


public class Waitress {
  private Menu<MenuItem> pancakeHouseMenu;
  private Menu<MenuItem> dinerMenu;

  public Waitress(Menu<MenuItem> pancakeHouseMenu, Menu<MenuItem> dinerMenu) {
    this.pancakeHouseMenu = pancakeHouseMenu;
    this.dinerMenu = dinerMenu;
  }

  public void printMenu() {
    Iterator<MenuItem> pancakeIterator = pancakeHouseMenu.createIterator();
    Iterator<MenuItem> dinerIterator = dinerMenu.createIterator();
    System.out.println("MENU\n----\nBREAKFAST");
    printMenu(pancakeIterator);
    System.out.println("\nLUNCH");
    printMenu(dinerIterator);

  }

  private void printMenu(Iterator<MenuItem> iterator) {
    while (iterator.hasNext()) {
      MenuItem menuItem = iterator.next();
      System.out.print(menuItem.getName() + ", ");
      System.out.print(menuItem.getPrice() + " -- ");
      System.out.println(menuItem.getDescription());
    }
  }
}
Copy after login

As can be seen from the above code, the waiter does not target Specific menu programming relies on a Menu interface that creates a menu iterator and an iterator interface Iterator for programming. The waiter does not need to know what kind of assembly method the menu is passed, but only needs to use The menu objects that implement these two interfaces can be traversed, which achieves the purpose of implementing the interface by relying on polymorphism for changes, and the purpose of implementing the interface for unchanged dependence, thus achieving the separation of waiter and menu assembly methods.

The iterator pattern can be seen everywhere in the collection of Java class libraries. The Menu used here is equivalent to the Iterable interface in the Java class library. Its function is to create an iterator object, and the Iterator interface is the same as the Iterator interface of the Java class library. Basically the same. What needs to be explained here is that actually letting a class implement the iterator pattern not only adds functionality to a class, but also increases the maintenance burden of the class, because the basic method of the class is highly cohesive. The so-called cohesion is implementation A complete set of related functions, and the iterator interface is actually a complete set of related functions. Therefore, letting a class implement the iterator pattern implicitly adds two sets of less "cohesive" functions to the class. set of functions, which will lead to the need to take both sides into consideration when maintaining functions of this class. This is reflected in the Java class library ArrayList and LinkedList. It not only provides all the basic remove methods of List, but also provides the remove method that needs to be implemented by iterators. In order to achieve the unification of the two, it has to make some conventions. For example, when traversing a collection, you cannot call the basic remove or add methods of the class that will change the structure of the class.

The above is the detailed content of Detailed explanation of the use of iterators in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template