Iterators

You should be familair with using 'For' and 'For-each' loops for iterating through collections by now, but none of these provide a safe way of deleting an item from an ArrayList (or other collection) whilst iterating through it.

To safely delete from an array while iterating through it we can use an Iterator. An Iterator allows us to use a While loop to go through an array, but rather than using an index, we check if the iterator has a 'next' item, and then inside the loop we access this 'next' item.

An iterator should be created specifying the same 'type' as the items in your collection (in the same way an ArrayList declaration specifies a type). To use an iterator you should add an import statement at the top of the file:

import java.util.Iterator;
The following example shows to how to use an iterator to print all the items in an ArrayList:
//assumes namesList is an ArrayList<String>
Iterator<String> namesIterator = namesList.iterator();
while (namesIterator.hasNext()) {
    //be careful not to call the .next() method more than once in the loop accidentally
    String name = namesIterator.next();
    System.out.println(name);
}

Removing an item from a collection with an iterator

As soon as the iterator reaches the item we wish to delete (e.g. after a call to .next()), then we can call the remove() method on the iterator to remove it. The following code provides an example:

ArrayList<Integer> numbersList = new ArrayList<Integer>();
numbersList.add(3);
numbersList.add(7);
numbersList.add(6);

Iterator<Integer> numberIterator = numbersList.iterator();
while (numberIterator.hasNext()) {
    Integer number = numberIterator.next();
    if (number % 3 != 0){
        numberIterator.remove();
    }
}
//numberList will now contain only 3 and 6

Task - deletion of invalid tweets

Create a modified version of the valid tweets task from the Searching Arrays tutorial that removes Strings longer than 140 characters from the ArrayList passed in (i.e. do not create a new ArrayList). As the method is modifying the ArrayList itself (and not a copy), it should not return a value, however you should test to verify the contents of the array have been modified after the method has been called.

Task

Modify the programme you wrote for managing names of animals at the zoo. Devise an option whereby the user can be shown each name in in the ArrayList, and be prompted as to whether they wish to delete it - ensure you use an Iterator.