This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Default capacity and load factor" Watch "Default capacity and load factor" New topic
Author

Default capacity and load factor

Rekha Anand
Ranch Hand

Joined: Feb 23, 2008
Posts: 36
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

Joined: Mar 10, 2008
Posts: 1756
    
    7

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.


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!!

Rekha
 
 
subject: Default capacity and load factor
 
Similar Threads
Dan's new Collections Questions
help needed
What are the new Topics in SCJP 1.4 Exam
Doubt in ejb
WeakHashMap