60 likes | 205 Views
ITERATORS. Methods. The standard iterator has 3 basic methods. -next(): advances the iterator one element up and returns the object that it passed over. - hasNext ():returns true if there is an element after the iterator’s position, else it will return false .
E N D
Methods • The standard iterator has 3 basic methods -next(): advances the iterator one element up and returns the object that it passed over -hasNext():returns true if there is an element after the iterator’s position, else it will return false -remove(): removes and returns the last element that was passed over by next()
Implementations • Here is an example of how we can use the iterator to display every element in the list
Your list with elements represented with the letter e Here it is true e1 e2 e3 e4 e5 e6 while(hasNext()) – this checks throughout the loop if there is an element following the iterator Because it is true, we can call the next() method and advance the iterator forward After we call next(), we call the remove() method and take away element that we passed over. We can repeat these steps in a loops to remove all of the elements We now add an iterator to the list by using the list.iterator() method We can use the 3 previously mentioned methods in a loop to systematically return and remove the elements form the list When called the iterator always starts at the position before the first element Once we reach the end, our list is empty and the loop finishes
HUZZAH NOW YOU’RE THINKING WITH ITERATORS