Junior — Middle
How is the capacity determined in ArrayList and HashSet data structures?
sobes.tech AI
Answer from AI
In Java, capacity is the number of elements that a data structure can hold without needing to expand its internal array.
ArrayList:
- An ArrayList internally stores an array of objects.
- When creating an ArrayList without specifying an initial capacity, a default value is used (usually 10).
- When adding elements, if the current array is full, the capacity increases (usually by about 1.5 times), a new larger array is created, and the elements are copied into it.
HashSet:
- HashSet is implemented based on HashMap.
- The capacity of a HashSet is the capacity of its internal HashMap, which is based on an array of buckets.
- When creating a HashSet, you can specify an initial capacity and a load factor.
- If the number of elements exceeds (capacity * load factor), the capacity is expanded (the number of buckets is increased), which affects the performance of operations.
Thus, capacity is the internal size of the array or buckets, which influences performance and the need for memory reallocation when adding new elements.