Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

iterate thru HashMap

 
lavnish lalchandani
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the following code




gives me output

3...object name t-h-r-e-e
2...object name t-w-o
1...object name o-n-e

but what i want is

1...object name o-n-e
2...object name t-w-o
3...object name t-h-r-e-e

I need the above output for correct functionality of my application ...
am ok in using another collection object .. like HashTable !!
how do i achieve the above output
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by lavnish lalchandani:
how do i achieve the above output


By not using a HashMap !
From the java doc for HashMap
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.


If order is important use a LinkedHashMap
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Joanne]: If order is important use a LinkedHashMap

Or possibly a TreeMap. In this example they will both give the same output. But if you change

to

then the LinkedHashMap will iterate in the order the items were added (3-2-1) while the TreeMap will iterate in the natural order of the keys (1-2-3). Choose whichever behavior seems more appropriate for your application.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic