File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Default capacity and load factor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Default capacity and load factor" Watch "Default capacity and load factor" New topic

Default capacity and load factor

Rekha Anand
Ranch Hand

Joined: Feb 23, 2008
Posts: 36
Hello All,

As per

the default initial capacity of a LinkedHashSet is 16. So, if I construct a new LinkedHashSet as below...
LinkedHashSet lhset = new LinkedHashSet();

The default capacity of lhset will be 16. I tried adding 20 elements in lhset. All the elements were added without any problem.

Q. Does this mean the collections increase their size automatically?

Q. size and capacity are two different parameters of any collection. After adding 20 elements, i got lhset.size() == 20. How do I find the "capacity" of lhset?

Jelle Klap

Joined: Mar 10, 2008
Posts: 1951

A HashSet uses a HashMap internally that has a default capacity of 16 and a load factor of 0.75f. The capacity is not a hard limit after which no more elements can be added. The HashMap maintains an internal threshold flag that, when reached, triggers a resize action, which results of a new capacity that is equal to the capacity multiplied by the load factor.


Q1: Correct, for all intents and puroses, the capacity of the HashSet is dynamically increased.

Q2: The size, as in number of elements in the HashSet, can be easily retrieved using the HashSet.size() method. There isn't really an easy way to retrieve the capacity, but there's really no need to either. If you absolutely desperately want to, I guess you could retrieve the backing HashMap using reflection and determine the capacity of the HashMap in the same manner.

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Rekha Anand
Ranch Hand

Joined: Feb 23, 2008
Posts: 36
Thanks for the help!!

I agree. Here's the link:
subject: Default capacity and load factor
It's not a secret anymore!