From the course: Java Design Patterns: Behavioral Part 1

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Creating an iterator

Creating an iterator - Java Tutorial

From the course: Java Design Patterns: Behavioral Part 1

Start my 1-month free trial

Creating an iterator

- [Tutor] I want to be able to iterate over my collection of items using the iterator pattern. So the first thing I'm going to do now is I'm going to create a class to do the iteration. So I'm going to create a new Java class and I'm going to call it stock iterator. Again, I'm going to make use of the JDK classes. So I'm going to make this class implement iterator. Again, my IDE is showing me a warning, so if I hover over it, I can see that I need to implement some methods from iterator. So again, I'm going to use the keyboard shortcut alt enter and choose implement methods. The ones I need are has next, next, and remove. So I'm going to select all of those and click okay. Before I go and fill out these methods, I need to create some fields for this class. So the first one is going to be a field of type inventory, which are called inventory. And I need this because the iterator needs to know about the collection it's…

Contents