-1

We can print Linked list with Iterator and for loop. How does it differ as far as memory allocation is concerned? Which one is more effective?

public class Demo {
    public static void main(String[] args) {
        LinkedList<String> placesToVisit = new LinkedList<String>();
        placesToVisit.add("Sydney");
        placesToVisit.add("Melbourne");
        placesToVisit.add("Brisbane");
        placesToVisit.add("Perth");

        printListWithoutFor(placesToVisit);
        printListWithFor(placesToVisit);

    }

    private static void printListWithoutFor(LinkedList<String> linkedList) {
        Iterator<String> i = linkedList.iterator();
        while (i.hasNext()) {
            System.out.println("Now visiting " + i.next());
        }
        System.out.println("=========================");
    }

    private static void printListWithFor(LinkedList<String> linkedList){
        for (int i=0; i<linkedList.size(); i++){
            System.out.println("Now visiting " + linkedList.get(i));
        }
    }
}
Jayveer Parmar
  • 500
  • 7
  • 25

2 Answers2

1

Printing with Iterator is more time efficient (since it iterates over the linked list just once, where each linkedList.get(i) requires partial iteration over the list), even though it requires a little more memory (for the allocation of the Iterator). I wouldn't choose a for loop over Iterator just to save that one instance allocation.

In terms of space complexity, both ways requires O(1) space.

Therefore you should prefer the method with the better time complexity - the print with Iterator takes O(n) time while the for loop takes O(n^2) time.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Just not only for memory concern but also to avoid indexing issues you can find iterator better than loops. please find more information here

Chetan chadha
  • 558
  • 1
  • 4
  • 19