Welcome to my Iterator Design Pattern Tutorial! The iterator design pattern allows you to access objects that are stored in many different collection types.
You do this by creating a common interface that these classes share. Then you have them provide you with an iterator that allows you to traverse the objects they contain.
Because they all share a common interface you can treat them polymorphically and eliminate a lot of duplicate code. The example video will explain how and the code that follows will reenforce the concepts.
If you like videos like this, it helps to tell Google [googleplusone]
Share it if you think others will find it useful
Code from the Video
SONGINFO.JAVA
// Will hold all of the info needed for each song // I told all users to: // 1. create a function named addSong() for adding song, band and release // 2. create a function named getBestSongs() that will return the collection // of songs public class SongInfo{ String songName; String bandName; int yearReleased; public SongInfo(String newSongName, String newBandName, int newYearReleased){ songName = newSongName; bandName = newBandName; yearReleased = newYearReleased; } public String getSongName(){ return songName; } public String getBandName(){ return bandName; } public int getYearReleased(){ return yearReleased; } }
SONGSOFTHE70S.JAVA
import java.util.ArrayList; import java.util.Iterator; public class SongsOfThe70s implements SongIterator{ // ArrayList holds SongInfo objects ArrayList<SongInfo> bestSongs; public SongsOfThe70s() { bestSongs = new ArrayList<SongInfo>(); addSong("Imagine", "John Lennon", 1971); addSong("American Pie", "Don McLean", 1971); addSong("I Will Survive", "Gloria Gaynor", 1979); } // Add a SongInfo object to the end of the ArrayList public void addSong(String songName, String bandName, int yearReleased){ SongInfo songInfo = new SongInfo(songName, bandName, yearReleased); bestSongs.add(songInfo); } // Get rid of this // Return the ArrayList filled with SongInfo Objects public ArrayList<SongInfo> getBestSongs(){ return bestSongs; } // NEW By adding this method I'll be able to treat all // collections the same public Iterator createIterator() { // TODO Auto-generated method stub return bestSongs.iterator(); } }
SONGSOFTHE80S.JAVA
import java.util.Arrays; import java.util.Iterator; public class SongsOfThe80s implements SongIterator{ // Create an array of SongInfo Objects SongInfo[] bestSongs; // Used to increment to the next position in the array int arrayValue = 0; public SongsOfThe80s() { bestSongs = new SongInfo[3]; addSong("Roam", "B 52s", 1989); addSong("Cruel Summer", "Bananarama", 1984); addSong("Head Over Heels", "Tears For Fears", 1985); } // Add a SongInfo Object to the array and increment to the next position public void addSong(String songName, String bandName, int yearReleased){ SongInfo song = new SongInfo(songName, bandName, yearReleased); bestSongs[arrayValue] = song; arrayValue++; } // This is replaced by the Iterator public SongInfo[] getBestSongs(){ return bestSongs; } // NEW By adding this method I'll be able to treat all // collections the same @Override public Iterator createIterator() { // TODO Auto-generated method stub return Arrays.asList(bestSongs).iterator(); } }
SONGSOFTHE90S.JAVA
import java.util.Hashtable; import java.util.Iterator; public class SongsOfThe90s implements SongIterator{ // Create a Hashtable with an int as a key and SongInfo // Objects Hashtable<Integer, SongInfo> bestSongs = new Hashtable<Integer, SongInfo>(); // Will increment the Hashtable key int hashKey = 0; public SongsOfThe90s() { addSong("Losing My Religion", "REM", 1991); addSong("Creep", "Radiohead", 1993); addSong("Walk on the Ocean", "Toad The Wet Sprocket", 1991); } // Add a new SongInfo Object to the Hashtable and then increment // the Hashtable key public void addSong(String songName, String bandName, int yearReleased){ SongInfo songInfo = new SongInfo(songName, bandName, yearReleased); bestSongs.put(hashKey, songInfo); hashKey++; } // This is replaced by the Iterator // Return a Hashtable full of SongInfo Objects public Hashtable<Integer, SongInfo> getBestSongs(){ return bestSongs; } // NEW By adding this method I'll be able to treat all // collections the same public Iterator createIterator() { // TODO Auto-generated method stub return bestSongs.values().iterator(); } }
DISCJOCKEY.JAVA
import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; public class DiscJockey { SongsOfThe70s songs70s; SongsOfThe80s songs80s; SongsOfThe90s songs90s; // NEW Passing in song iterators SongIterator iter70sSongs; SongIterator iter80sSongs; SongIterator iter90sSongs; /* OLD WAY public DiscJockey(SongsOfThe70s newSongs70s, SongsOfThe80s newSongs80s, SongsOfThe90s newSongs90s) { songs70s = newSongs70s; songs80s = newSongs80s; songs90s = newSongs90s; } */ // NEW WAY Initialize the iterators public DiscJockey(SongIterator newSongs70s, SongIterator newSongs80s, SongIterator newSongs90s) { iter70sSongs = newSongs70s; iter80sSongs = newSongs80s; iter90sSongs = newSongs90s; } public void showTheSongs(){ // Because the SongInfo Objects are stored in different // collections everything must be handled on an individual // basis. This is BAD! ArrayList aL70sSongs = songs70s.getBestSongs(); System.out.println("Songs of the 70s\n"); for(int i=0; i < aL70sSongs.size(); i++){ SongInfo bestSongs = (SongInfo) aL70sSongs.get(i); System.out.println(bestSongs.getSongName()); System.out.println(bestSongs.getBandName()); System.out.println(bestSongs.getYearReleased() + "\n"); } SongInfo[] array80sSongs = songs80s.getBestSongs(); System.out.println("Songs of the 80s\n"); for(int j=0; j < array80sSongs.length; j++){ SongInfo bestSongs = array80sSongs[j]; System.out.println(bestSongs.getSongName()); System.out.println(bestSongs.getBandName()); System.out.println(bestSongs.getYearReleased() + "\n"); } Hashtable<Integer, SongInfo> ht90sSongs = songs90s.getBestSongs(); System.out.println("Songs of the 90s\n"); for (Enumeration<Integer> e = ht90sSongs.keys(); e.hasMoreElements();) { SongInfo bestSongs = ht90sSongs.get(e.nextElement()); System.out.println(bestSongs.getSongName()); System.out.println(bestSongs.getBandName()); System.out.println(bestSongs.getYearReleased() + "\n"); } } // Now that I can treat everything as an Iterator it cleans up // the code while allowing me to treat all collections as 1 public void showTheSongs2(){ System.out.println("NEW WAY WITH ITERATOR\n"); Iterator Songs70s = iter70sSongs.createIterator(); Iterator Songs80s = iter80sSongs.createIterator(); Iterator Songs90s = iter90sSongs.createIterator(); System.out.println("Songs of the 70s\n"); printTheSongs(Songs70s); System.out.println("Songs of the 80s\n"); printTheSongs(Songs80s); System.out.println("Songs of the 90s\n"); printTheSongs(Songs90s); } public void printTheSongs(Iterator iterator){ while(iterator.hasNext()){ SongInfo songInfo = (SongInfo) iterator.next(); System.out.println(songInfo.getSongName()); System.out.println(songInfo.getBandName()); System.out.println(songInfo.getYearReleased() + "\n"); } } }
RADIOSTATION.JAVA
public class RadioStation { public static void main(String[] args){ SongsOfThe70s songs70s = new SongsOfThe70s(); SongsOfThe80s songs80s = new SongsOfThe80s(); SongsOfThe90s songs90s = new SongsOfThe90s(); DiscJockey madMike = new DiscJockey(songs70s, songs80s, songs90s); // madMike.showTheSongs(); madMike.showTheSongs2(); } }
SONGITERATOR.JAVA
import java.util.Iterator; public interface SongIterator { public Iterator createIterator(); }
Just wanted to say thanks for all your work.
So thanks.
You’re very welcome and thank you for taking the time to show your appreciation 🙂
Great job! very nice stuff on design patterns. Thanks a ton.
You’re very welcome 🙂 I’m finishing up object oriented design today. Then the next tutorial will be on code refactoring, which will help you incorporate design patterns into your designs.
WoooW , This is absolutely Great .
Thank you so much sir ,
Hats Off 🙂
You’Re The Man , You’Re The Best .
Keep up the good work !
You are very welcome 🙂
Derek,
I have always found your videos and code on design patterns to be very concise and to the point. Please continue your good work, and thanks a ton !
Sudhakaran
Thank you. I’m glad you liked them. You’re very welcome 🙂
Another Great article.. Thoroughly explained..
Thank you 🙂
Thank you
because description very nice
You’re very welcome 🙂
Derek you are just amazing 😀
Thank you 🙂 I try to do my best
really swift,fast and great tutorials, u r simply great dude!
Thank you very much 🙂 I do my best to make original tutorials
great job…thanks for ur time
Another great tutorial! You make it look so easy! Thanks again!
Thank you very much 🙂 I have been doing this stuff forever. Stick with it and you’ll be better then me some day
Thanks great tutorials, please keep up the good work
Thank you and you’re very welcome 🙂
Hello. Great job. Mr Derek. Can u share the UML schema of that design Pattern too ? I did. And i want check mine.
Thank you 🙂 I’m not sure what schema you want. I have the whole presentation if you want that.
UML schema like Factory Method. Most of your tutorials you used the UML diagrams. But in there after explanation you passed directly to code )) I understand everythink. But if u can plz send me full presentation
Here is a link to the whole presentation. It is a bit messy because I never planned on giving it away, but everything is there.
Thank uu . U r great man 🙂 U r doing the best thing in the world.
Thank you 🙂 You’re very kind to say that.
Thank you SO MUCH for all your veideos. I am amazed that people take their time to do this for everyone to benefit. I feel like you are providing great content and great help. Thank you so much!
P.S. This helps a lot with exam revision too!
You’re very welcome 🙂 I have continued to do this because I have found so many wonderful people on the internet that I have not found any place else. I’m more then happy to help.
You are a god;)
I try to do my best 🙂 I’m glad you liked it
you’re awesome! i watched practically all your design patterns videos.thumbs up! 😉
Thank you 🙂 I’m glad they helped
Actually you’ve created a new Learning pattern ;). Doesn’t matter How much complicated the topic is, just watch the video once and then go through the code, you get it. Good work Derek!
Thank you for the compliment 🙂 That is the idea behind making each video.