Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Default capacity and load factor

 
Rekha Anand
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,

As per
http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedHashSet.html

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?

Regards,
Rekha
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

So:

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.
 
Rekha Anand
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help!!

Rekha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic