wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Iterating a hashmap using Iterator is efficient than using foreach loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Iterating a hashmap using Iterator is efficient than using foreach loop" Watch "Iterating a hashmap using Iterator is efficient than using foreach loop" New topic
Author

Iterating a hashmap using Iterator is efficient than using foreach loop

Balaguru Gupta
Greenhorn

Joined: Mar 03, 2013
Posts: 10
Can anyone explain why Iterating a hashmap using Iterator is efficient than using foreach loop?
Muneeswaran Balasubramanian
Ranch Hand

Joined: Mar 19, 2010
Posts: 138
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,,,,,


Cheers Munees
My Blog
Balaguru Gupta
Greenhorn

Joined: Mar 03, 2013
Posts: 10
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?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14194
    
  20

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Balaguru Gupta
Greenhorn

Joined: Mar 03, 2013
Posts: 10
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
 
GeeCON Prague 2014
 
subject: Iterating a hashmap using Iterator is efficient than using foreach loop