Use an Iterator to cycle through a collection in the forward direction.
// Use a ListIterator to cycle through a collection in the reverse direction.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
class Employee {
String name;
String number;
Employee(String n, String num) {
name = n;
number = num;
}
}
public class Main {
public static void main(String args[]) {
LinkedList<Employee> phonelist = new LinkedList<Employee>();
phonelist.add(new Employee("A", "1"));
phonelist.add(new Employee("B", "2"));
phonelist.add(new Employee("C", "3"));
Iterator<Employee> itr = phonelist.iterator();
Employee pe;
while (itr.hasNext()) {
pe = itr.next();
System.out.println(pe.name + ": " + pe.number);
}
ListIterator<Employee> litr = phonelist.listIterator(phonelist.size());
while (litr.hasPrevious()) {
pe = litr.previous();
System.out.println(pe.name + ": " + pe.number);
}
}
}
Related examples in the same category