How to get the initial value when creating a collection

List list = new ArrayList (5);

I’m developing a set initialization related rule, I can’t get ‘5’ when creating a set.
Besides ArrayList, can other sets such as LinkedList, TreeSet, and HashSet also get the initial value in the same way?
If there is any way to tell me this place, I will be grateful.

1 Like


What language are you writing the rule for? I guess Java?


Hi, Ann,

You’re right. It’s Java. I’m sorry I didn’t describe my situation clearly before.


Hello @KevinJin, can you share more details about the rule you’re implementing in order to help you?

Meanwhile, it’s useful to know that not all the Collections in Java have the concept of capacity. Java Collections are dynamic, meaning that their size can grow, and shrink, over time depending on the internal data structure used to store the data.

Collections that use an array as a data structure to store the elements have the concept of capacity. For example ArrayList is re-sized over time depending on the number of elements added to, or removed from the collection. Have a look at OpenJDK to understand how this is implemented in OpenJDK.

Collections, like LinkedList and TreeSet, that use a linked list data structure to store the elements don’t have any concept of capacity because the linked list is dynamic by nature and doesn’t pre-allocate any fixed memory, differently from what arrays do.