Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default capacity of collection framework classes?

Tags:

java

I know that the default capacity of Vector class in java is 10 and similarly ArrayList also have it's default capacity 10. But what is the default capacity of the following classes:

  1. Vector
  2. ArrayList
  3. LinkedList
  4. HashMap
  5. LinkedHashMap
  6. ConcurrentHashMap
  7. HashSet
  8. LinkedHashSet
  9. TreeSet

Or is there any other way to get the default capacity of all collection framework classes in java?

like image 672
Sudhir Ojha Avatar asked Oct 03 '18 13:10

Sudhir Ojha


People also ask

What is the default size of collection?

24) What is the default size of load factor in hashing based collection? The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12.

What is default capacity in Java?

Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10.

What is the default size of Hashtable in collection framework?

Constructs a new, empty hashtable with a default initial capacity (11) and load factor (0.75).

What is the default capacity of set?

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).


2 Answers

There is no one correct answer here as it will depend on the Java version. For example RFR JDK-7143928 : (coll) Optimize for Empty ArrayList and HashMap made ArrayList and HashMap empty by default in Java 8.

You would have to check the default constructor for each of the mentioned classes in your JDK. In theory this could also vary between JDK build (e.g. Oracle, IBM, Azul...) as default ArrayList capacity is not part of Java Language Specification.

like image 154
Karol Dowbecki Avatar answered Sep 18 '22 00:09

Karol Dowbecki


 1. Vector = 10
 2. ArrayList = 10
 3. LinkedList - does not have a capacity
 4. HashMap = 16 (but with the default load factor of 0.75, only 12 can be populated before a resize will happen)
 5. LinkedHashMap = 16 (read above)  
 6. ConcurrentHashMap = 16
 7. HashSet = 16 (it's  based on a HashMap)
 8. LinkedHashSet = 16
 9. TreeSet = does not have one

Just notice that some of them are lazy and all of them are subject to change from release to release.

like image 37
Eugene Avatar answered Sep 20 '22 00:09

Eugene