Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

asked on

iterating over elements of a HashMap

Hi,

I made a HashMap<String, Integer>. I want to iterator over all elements.

for (Iterator it = m_Table.values().iterator(); it.hasNext();) {
    Map.Entry entry = (Map.Entry)it.next();
    String strKey = (String)entry.getKey()
    Integer nData = (Integer)entry.getValue() ;
}

This causes a runtime exception though... what's the right way to do it?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of ksivananth
ksivananth
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

ASKER

Hmm they work. But I don't get the order in which the keys are extracted. In my HashMap, I have keys:

"xy"
"z"

That was the order in which they were entered into the map too. But when I iterate over them, they come out in:

"z"
"xy"

order?

Thanks
hashmap don't maintain the order, try using tree map!
sorry looks like, that will keep in a sorting order!
HashMap will not return the entries in order in which they were inserted..

If you want the same order in which you inserted, then you have to use.. LinkedHashMap
try use LinkedHashMap!
Ok I wrote my whole app (which is not that big really) using HashMap. The only operations I used from HashMap were get() and put().

So by switching the LinkedHashMap, I shouldn't have to change any of my use calls, right? The only difference is that now when I iterate over the elements, they'll come out in the order inserted?

Thanks
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
LinkedHashMap class is inherited from HashMap class