• Post Reply Bookmark Topic Watch Topic
  • New Topic

displaying key of a hashmap,wrong order  RSS feed

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
its solved..........use
HashMap map=new LinkedHashMap();
 
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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 ?
 
biswajit goswami
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that part was already done......sorted resultset populates the map
 
Ranch Hand
Posts: 687
Hibernate jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!