• Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting Improper order of Key in HashMap.  RSS feed

 
SunilK Chauhan
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kindly review my code as shown below.




Here Output is shown as [3, 2, 1, 4].
But it's not the proper order of data as we stored in HashMap is [1,2,3,4] for Keys.

Why i am getting such improper order of Keyset?
 
Paweł Baczyński
Bartender
Posts: 2054
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because HashMap doesn't specify any particular iteration order.
As per javadoc:
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 you need the entries ordered, you need to use LinkedHashMap.
 
Knute Snortum
Sheriff
Posts: 4087
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you need the entries ordered, you need to use LinkedHashMap.

Or TreeMap.
 
Paweł Baczyński
Bartender
Posts: 2054
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:Or TreeMap.

That depends on whether OP wants insertion order or sorted order.

I guessed the insertion order because with TreeMap the code below would print [1, 10, 2, 3, 4, 5, 6, 7, 8, 9].
 
Knute Snortum
Sheriff
Posts: 4087
112
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're right. "Improper order" is a little ambiguous.
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:You're right. "Improper order" is a little ambiguous.

But the OP isn't:
it's not the proper order of data as we stored in HashMap is [1,2,3,4] for Keys...

So LinkedHashMap should work just fine.

Winston
 
Paul Clapham
Sheriff
Posts: 22509
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, that sort of implies that insertion order is the correct order, but due to the OP's lack of grammatical-ness it's still possible that sorted order is correct, in which case TreeMap would be the answer. We haven't been given enough information, but presumably the OP knows what they meant.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!