1

When We have for lop then why we have use iterator following code are some working as Result give by iterator

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, String> hasmap  = new HashMap<String, String>();
        hasmap.put("1", "Java");
        hasmap.put("2", ".Net");
        hasmap.put("3", "C++");
        hasmap.put("4", "Pearl");
        hasmap.put("5", "PHP");

        for (Entry<String, String> entry : hasmap.entrySet()) {

                System.out.println("For Loop Get Key"+entry.getKey());
                System.out.println("For Loop Get Value"+entry.getValue());

        }
        Set set = hasmap.entrySet();
        Iterator itr =  set.iterator();
        while(itr.hasNext()){
            Map.Entry map = (Entry) itr.next();
            System.out.println(map.getKey());
            System.out.println(map.getValue());
        }


    }   

}
JDevil
  • 169
  • 3
  • 14
  • 9
    Accessing the underlying iterator permits you to safely remove elements from the map while iterating. This is not possible with the for-each loop, which is basically a read-only operation on your data-structure. So if your intent is to print the content, use the for-each loop. Less code to write and less error prone. – Alexis C. Mar 27 '15 at 13:01
  • try to just print "Hello World " 1000 times. or assign random value to a int array of 1000 lenght. – Saif Mar 27 '15 at 13:04
  • The iterator was there well before the enhanced for-each loop was introduced.in Java 5. – assylias Mar 27 '15 at 13:08

3 Answers3

3

The version of the iterative loop you have in your post is a matter of historical use; the foreach loop was introduced in Java 1.5.

Until that point, foreach loops were achieved using the Iterator construct (which has been available since Java 1.2).


One reason to use Iterator is for its .remove() method, which safely removes an element without throwing a ConcurrentModificationException, which is thrown whenever a loop is modified while it is being iterated (which is not allowed in Java).

On the other hand, simple foreach loops in Java are read only, but are more succinct and generally result in cleaner, easier to read code:

for (String str : array) {
  System.out.println(str);
}

versus

Iterator<String> arrayItr = array.iterator();
while (arrayItr.hasNext()) {
  String str = arrayItr.next();
  System.out.println(str);
}
Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
0

From my point of view, when we think about Iterator below are advantages of iterator and not available in for loop concept:

  1. remove() option is available in Iterator.
  2. Fail fast and Fail Safe iterator are available in Iterator concept.
Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
Subbu
  • 308
  • 2
  • 4
  • 12
0

From this answer: How does the Java 'for each' loop work?

The for-each loop can only iterate over an object that is an array or in instance of Iterable. Thus the iterator of the object is used in the for-each loop, but you cannot call i.remove() because the iterator is merely inferred.

for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
    String item = i.next();
    System.out.println(item);
}
Community
  • 1
  • 1
Ian2thedv
  • 2,691
  • 2
  • 26
  • 47