Java ListIterator for Forward and Backward Traversal

Day 63 of Sharing What I’ve Learned 🚀 Two-Way Traversal in Java — Going Forward and Backward with ListIterator After understanding how Iterator helps traverse collections safely, I explored something even more powerful — traversing a list in both directions. And that is where ListIterator comes in. Unlike Iterator, which moves only forward, ListIterator gives us the flexibility to: move forward move backward add elements update elements remove elements safely That makes it especially useful when working with List implementations like ArrayList and LinkedList. 🔹Why it matters Sometimes, data is not just meant to be read from top to bottom. In real applications, we may need to: revisit previous elements make changes while traversing move in both directions without restarting the loop That is exactly what makes ListIterator so useful. 🔹Key methods hasNext() → checks if next element exists next() → moves forward hasPrevious() → checks if previous element exists previous() → moves backward add() → inserts element set() → updates current element remove() → deletes element safely 🔹Simple example import java.util.*; public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C++"); ListIterator<String> it = list.listIterator(); System.out.println("Forward traversal:"); while (it.hasNext()) { System.out.println(it.next()); } System.out.println("Backward traversal:"); while (it.hasPrevious()) { System.out.println(it.previous()); } } } 🔹My realization Iterator taught me how to traverse safely. ListIterator taught me how to traverse smartly. 👉 Forward only is useful 👉 Forward + backward gives more control 👉 More control means more flexibility in programming Today I understood that Java collections are not just about storing data — they are also about navigating it in the right way. #Java #Collections #ListIterator #Iterator #Programming #DataStructures #100DaysOfCode #DeveloperJourney #Day63 Grateful for guidance from TAP Academy Sharath R kshitij kenganavar

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories