File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes displaying key of a hashmap,wrong order Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "displaying key of a hashmap,wrong order" Watch "displaying key of a hashmap,wrong order" New topic
Author

displaying key of a hashmap,wrong order

biswajit goswami
Ranch Hand

Joined: Dec 05, 2005
Posts: 35
hi,
A hashmap is a form attribute(say mapObject) and contains two key value pairs,say{(a,0),(b,0)}.....sorted
i am displaying the key in jsp by:
<logic:iterate id="map" name="myForm" property="mapObject">
<bean:write name="map" property="key"/>
</logic:iterate>


o/p:
b
a

ok,modify the map.........{(a,0),(b,0),(c,0)}

o/p:
b
c
a


its seems that the key is picked from the map randomly,although its sorted there.

can anyone throw light??
biswajit goswami
Ranch Hand

Joined: Dec 05, 2005
Posts: 35
its solved..........use
HashMap map=new LinkedHashMap();
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

although its sorted there

Why do you think there are sorted ? Do you think the items are magically sorted for you ? Or are actually calling something like Collections.sort ?


[My Blog]
All roads lead to JavaRanch
biswajit goswami
Ranch Hand

Joined: Dec 05, 2005
Posts: 35
that part was already done......sorted resultset populates the map
Devesh H Rao
Ranch Hand

Joined: Feb 09, 2002
Posts: 687

Originally posted by biswajit goswami:
that part was already done......sorted resultset populates the map


From Java API

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

The sort is lost when the data is set in the hashmap, you need to explicitly sort the collection or use some other container than a hash[map,table] to store the data as the order can be lost.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: displaying key of a hashmap,wrong order