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
I made a HashMap<String, Integer>. I want to iterator over all elements.
for (Iterator it = m_Table.values().iterator(
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
If you want the same order in which you inserted, then you have to use.. LinkedHashMap
try use LinkedHashMap!
ASKER
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
LinkedHashMap class is inherited from HashMap class
ASKER
"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