• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Default capacity and load factor

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for the help!!

Rekha
 
reply
    Bookmark Topic Watch Topic
  • New Topic