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

Detailed explanation of the use of iterators in Java

Sep 23, 2017 am 10:13 AM
java use Detailed explanation

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles