• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Iterating a hashmap using Iterator is efficient than using foreach loop

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anyone explain why Iterating a hashmap using Iterator is efficient than using foreach loop?
 
Ranch Hand
Posts: 138
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Balaguru,


Foreach loop only used for Iteration.That means readonly.

But using iterator we can modify the collection using the method remove of Iterator.

This point add the value to your post.Waiting for others quotes,,,,,
 
Balaguru Gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you so much Muneeswaran,

I worked out with the same.
Example program ,

Apart from this reason, Is there any other difference for the same to justify that Iterator is efficient than foreach loop?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Balaguru Gupta wrote:Can anyone explain why Iterating a hashmap using Iterator is efficient than using foreach loop?


Why do you think that this is true? Because it isn't.

Note that a foreach loop will use an iterator "under the covers" - the compiler will generate code that loops over the map using an iterator. The foreach syntax is just to make it easier for you to write the code.

You should normally use the foreach loop syntax, because it's clearer and shorter to write. But if you need to remove elements from the map while you're iterating, you have to use the iterator syntax, because you need to be able to call remove() on the iterator, as you demonstrated in your code.
 
Balaguru Gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Jesper de Jong,

Thank you so much. Now I am pretty much clear with the concept and difference between using Iterator and foreach.

Cheerz mate
reply
    Bookmark Topic Watch Topic
  • New Topic