3

Below are the scenario of iterator and for loop:

1) Using iterator:

  ihm.put("Zara", new Double(3434.34));
  ihm.put("Mahnaz", new Double(123.22));
  ihm.put("Ayan", new Double(1378.00));
  ihm.put("Daisy", new Double(99.22));
  ihm.put("Qadir", new Double(-19.08));

  // Get a set of the entries
  Set set = ihm.entrySet();

  // Get an iterator
  Iterator i = set.iterator();

  // Display elements
  while(i.hasNext()) {
     Map.Entry me = (Map.Entry)i.next();
     System.out.print(me.getKey() + ": ");
     System.out.println(me.getValue());
  }
  System.out.println();

=====================================

Using For Loop:

    HashMap<String, Integer> map = new HashMap<String, Integer>();

    //Adding key-value pairs

    map.put("ONE", 1);

    map.put("TWO", 2);

    map.put("THREE", 3);

    map.put("FOUR", 4);

    //Adds key-value pair 'ONE-111' only if it is not present in map

    map.putIfAbsent("ONE", 111);

    //Adds key-value pair 'FIVE-5' only if it is not present in map

    map.putIfAbsent("FIVE", 5);

    //Printing key-value pairs of map

    Set<Entry<String, Integer>> entrySet = map.entrySet();

    for (Entry<String, Integer> entry : entrySet) 
    {
        System.out.println(entry.getKey()+" : "+entry.getValue());
    }        
}    

In the above both cases iterator and for loop are doing the same job.So can anyone tell me what is the differences between them and when i can use iterator and for loop.

Chandan
  • 129
  • 1
  • 1
  • 5
  • the only difference is *using iterator is like breathing through nose and using for loop is like breathing through mouth* ;) –  Oct 12 '16 at 06:50
  • 1
    Possible duplicate - [iterator Vs for](http://stackoverflow.com/questions/22267919/iterator-vs-for) – Ravikumar Oct 12 '16 at 07:03
  • The second one is clearer and type checked. They both use Iterator in reality. – Peter Lawrey Oct 12 '16 at 08:23

1 Answers1

3

The only significant difference between loop and iterator (apart from readability) is that while using iterator you can edit content of the collection through that Iterator instance.

If you try to edit map while looping through it you will get Concurrent ModificationException

You should use iterator when you want to update map while iterating over it e.g. remove entries which match some conditions.

Iterator<Entry> it = map.iterator();
while(it.hasNext())
      if(check(it.next()))
           it.remove();

I have to note that for-loop is a syntactic sugar for iterator and in resulting bytecode they will look the same way.

Daniil Dubrovsky
  • 459
  • 7
  • 17
  • "while using iterator you can edit the content of map" - using the iterator that is. If you e.g. delete an entry not through the iterator, it will still throw an exception. – Fildor Oct 12 '16 at 07:19