tags:

views:

104

answers:

5

In java while using the HashMap, they are using the Iterator class. But I can't understand for what purpose they are using Iterator in HashMap?

+2  A: 

For iteration, maybe?

In general, iterators are used to "remember" a point in the collection, so that you can do something to a current element and then move iterator to the next element, and so on...

When you write a code like

for(Value val : collection) { doSomething(val); }

You are implicitly using the collection's iterator. It is roughly equivalent to writing something like

Iterator<Value> i = collection.iterator();
while(i.hasNext())
{
    Value val = i.next();
    doSomething(val);
}
Rotsor
+3  A: 

Entries in a Map are made up of key/value pairs. Iterators can be used to cycle through the set of keys (Map.keySet().iterator()), the set of values (Map.values().iterator(), or both (via the entrySet() method and the Map.Entry<K,V> interface).

Ash
A: 

You can iterate through the keys:

myMap.keySet().iterator();

Or you can iterate through the values:

myMap.values().iterator();

These two iterators offered by HashMap allow you to get values (for example) from the map even if you dont know the keys. Or even get a list of the keys.

Paul
+1  A: 

Iterators should e used to read the elements from any kind of Collections like ArrayList, HAshMap etc. They will help us to navigate through the Iterator Objects, if they are not there, how can we retrieve the elements from the collection?

harigm
A: 

Iterators provide a way to go over all elements in some order. Not very useful for HashMap, but for TreeMap iterator provides a way go over the elements in increasing order. Similarly for LinkedHashMap one can iterate the way it was inserted.

fastcodejava