We often want to do some task to each element of a list. This is known as iterating through the elements of the list. With a List, it is possible to do this using the following code:
for (int tPersonNumber = 0; tPersonNumber<tList.size(); tPersonNumber++) { final Person tPerson = (Person)tList.get(tPersonNumber); iProcessPerson(tPerson); }where iProcessPerson is a method that contains the code that we want to execute on each element of the list. Although this would be reasonably efficient for a list that is implemented as an ArrayList, for a LinkedList it is very inefficient. This is because a LinkedList is implemented as a doubly-linked list:
So, we will avoid calling get in a loop. A different approach uses the iterator method that is defined in the List interface:
Iterator tIterator = tList.iterator();No matter whether tList is pointing to an ArrayList object or a LinkedList object, the call of iterator will create information that enables the list to be iterated efficiently. Assuming tList is pointing to a LinkedList object, then, after the above statement has been executed, some sort of structure like the following will have been set up:
The call of iterator returns a pointer to an object which supports the Iterator interface. This interface has the methods documented at javaapi:java/util/Iterator.html.
The methods iterator, hasNext and next can be used as follows:
Iterator tIterator = tList.iterator(); while (tIterator.hasNext()) { final Person tPerson = (Person)tIterator.next(); iProcessPerson(tPerson); }The methods hasNext and next can be efficiently implemented: a call of hasNext just returns the value of pos<size, and a call of next just returns the value of the posth element of the shortcuts and also increases the value of pos by 1.