Bookmark Topic Watch Topic
  • New Topic

is HashMap() sorted on keys by default?

 
chintu reddy
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Report post to moderator
All the references and Sun Java docs state that HasMap() is unsorted. But when in my following code, HashMap() comes out sorted on keys automatically..



now lets say my resultset was like "(1, john), (3,paul) (2, robert)".. but 'studentsList' was in following format "(1, john),(2, robert), (3,paul) ". i.e. when I am putting records into HasMap it is sorting automatically.... Is this normal behavior of HashMaps? Are there any other collections/maps I can use to get around this?

Thanks in adv?
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Report post to moderator
chintu reddy wrote:All the references and Sun Java docs state that HasMap() is unsorted.


What the java docs actually say is
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.
In other words the Hashmap can order the keys however it wants and also change that order at any time.

chintu reddy wrote:Are there any other collections/maps I can use to get around this?


If you look at the Javadoc for the Map interface, it lists all the classes that implement it. TreeMap or LinkedHashMap are probably worth looking at.
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Report post to moderator
Use LinkedHashMap if you want to store your data in the order in which keys are inserted into the Map.
HashMap doesn't guarantee any order.
 
chintu reddy
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Report post to moderator
@Joanne & @Ireneusz.. thanks a lot folks... LinkedHashMap is exactly what I was looking for... thanks thanks
 
Campbell Ritchie
Sheriff
Pie
Posts: 49367
62
  • Mark post as helpful
  • send pies
  • Report post to moderator
Since you are asking essentially the same question here, in line with this FAQ, I am closing this thread.
 
Don't get me started about those stupid light bulbs.
    Bookmark Topic Watch Topic
  • New Topic