aspose file tools*
The moose likes Beginning Java and the fly likes is HashMap() sorted on keys by default? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic
Author

is HashMap() sorted on keys by default?

chintu reddy
Greenhorn

Joined: Feb 13, 2010
Posts: 21
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

Joined: Aug 05, 2005
Posts: 3580
    
  15
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.


Joanne
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
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

Joined: Feb 13, 2010
Posts: 21
@Joanne & @Ireneusz.. thanks a lot folks... LinkedHashMap is exactly what I was looking for... thanks thanks
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38910
    
  23
Since you are asking essentially the same question here, in line with this FAQ, I am closing this thread.
 
Consider Paul's rocket mass heater.
 
subject: is HashMap() sorted on keys by default?