3

I want to know why HashMap always takes a size which is multiple of 2 and why other collections do not?

What is the reason behind that?

Thanks

user1157635
  • 174
  • 1
  • 11

1 Answers1

-2

In fact, all the time the load of your HashMap go more than 75%, a HashMap is created with a double size. This is the reason why hashmap size is always a power of two. You might be interested by this article : http://java.dzone.com/articles/hashmap-internal

Luc DUZAN
  • 1,210
  • 9
  • 18
  • Then why this is not for other collections(Like hashtable etc) whose size got doubled when load factor passes. – user1157635 Jun 13 '14 at 09:01
  • In fact it the same, it just that for default initial size of HashMap is already a power of two so you get size = (2^DepSize)*2^(something) = 2^(K). But you can specify the initial size, http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html. So even for a HashMap you can have a size that is not a power of two, but it will always be something like K*2^something. – Luc DUZAN Jun 13 '14 at 09:25
  • Sorry Luc but my question is that there are other collections whose size when passed load factor got doubled but they does'nt use capacity in power of 2 alwayz like hashmap? – user1157635 Jun 13 '14 at 09:49
  • Hey Luc! finally got it. Tnx – user1157635 Jun 13 '14 at 12:54
  • `HashMap` actually does some math internally to use the smallest power-of-two capacity that's larger than the desired capacity. So you'll actually always have a power-of-two capacity – awksp Jun 13 '14 at 16:49