This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
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: 14114
    
  16

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 7 API documentation
Scala Notes - My blog about Scala
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Iterating a hashmap using Iterator is efficient than using foreach loop