Presents your JAVA E-NEWSLETTER for December 2, 2002 <-------------------------------------------> MODIFY A LIST WHILE ITERATING While the Iterator interface includes the remove method, sometimes you need to do more than just remove elements from a collection. If you happen to have a list, then you can use ListIterator. This is an extension of Iterator with extra methods to modify the list during iteration and to aid in the process. ListIterator adds six methods: four provide help when iterating, and two allow the list to be modified: boolean hasPrevious(); java.lang.Object previous(); int nextIndex(); int previousIndex(); void set(java.lang.Object); void add(java.lang.Object); Using these methods, you can walk backwards through a list: // get an Iterator starting at the end of the list ListIterator listItr = list.listIterator(list.size()-1); while(listItr.hasPrevious()) { System.err.println(listItr.previous()); } Or, you can avoid needing a counter in an iteration: // in this example we replace an element from one list // that passes an imaginary test in another list. ListIterator listItr = list.listIterator(); while(listItr.hasNext()) { Object obj = listItr.next(); if(someImaginaryTest(obj)) { // Replace at the same index. anotherList.set(listItr.previousIndex(), obj); } } Alternatively, you can modify the list you're iterating. One way in which to set all integers in a list to zero would be: ListIterator listItr = list.listIterator(); Integer zero = new Integer(0); while(listItr.hasNext()) { Object obj = listItr.next(); listItr.set(zero); } Lastly, ListIterator provides an add method. This method adds an object after your current position in the iteration, so you are setting the next object that will be seen. This can help to create on-the-fly processing. For example, to recursively iterate over all the files in a directory, you could use the following code: LinkedList list = new LinkedList(new File("/")); ListIterator listItr = list.listIterator(); while(listItr.hasNext()) { File file = (File)listItr.next(); if(file.isDirectory()) { // add all the files/directories to the list File[] contents = file.listFiles(); for(int i=0; i