Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Securing DevOps this week in the Security forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Hashtable  RSS feed

 
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The answer is [3 2 1]. But keySet prints the keys in the ascending order?
 
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hashtable is unordered, unsorted map.
 
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abhi it is a coincidence that you are getting the keys in descending order. But this behavior is not guaranteed as punit said. Hashtable is not sorted and ordered...
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But this co-incidence is not happening with HashMap(unordered as well).
When I try it using HashMap I get [ 1 2 3].
 
Ankit Garg
Sheriff
Posts: 9610
37
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Abhi an unordered collection also uses some internal order. That's why it doesn't give repeat objects will iterating. Since you are just adding objects of Integer class to the map, so the internal ordering of HashMap might be ordering it in natural order. That's why you are getting sorted result. But this behavior is not guaranteed. So for HashMap or Hashtable, you will have to say that they are unordered and unsorted no matter what the output is in your case. This is just one example where you are getting sorted result. So don't rely on it. Rely on documentation which says that HashMap and Hashtable are unordered ...
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok. Got it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!