This Java Example shows how to iterate through an ArrayList object in reverse direction using Java ListIterator's previous and hasPrevious methods .
import java.util.ArrayList; import java.util.ListIterator; public class TraverseReverseUsingListIteratorExample { public static void main(String[] args) { // create an ArrayList object ArrayList arrayList = new ArrayList(); // Add elements to Arraylist arrayList.add("1"); arrayList.add("2"); arrayList.add("3"); /** * listIterator(int index) - Returns a list iterator of the elements in * this list (in proper sequence), starting at the specified position in * this list.An initial call to the previous method would return the * element with the specified index minus one. **/ ListIterator listIterator = arrayList.listIterator(arrayList.size()); System.out.println("Arraylist in the reverse order: "); while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); } } }
The output is:
Arraylist in the reverse order:
3
2
1
No comments:
Post a Comment