Home > Software engineering >  The Collections in Java have limited capacity?
The Collections in Java have limited capacity?

Time:12-15

i'm reading about collections, namely, Vector in this moment, but i can't understand a part

Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.

I have been reading very little about collections in java, and the little I have seen I realize that they are dynamic, but until a moment I thought they were unlimited, I do not know if they are, this capacity and capacityIncrement confuse me, someone could explain me what they consist of please? :)

CodePudding user response:

You can add as many elements to a collection as you please. They are unlimited in that sense.

Some collections have an internal capacity, which describes how many elements the collection can hold without allocating more memory or rebuilding its internal data structures.

By setting the capacity correctly in advance, you can ensure that the collection doesn't need to allocate any more memory than necessary, or spend extra time rebuilding its data structures. Setting capacity is about optimizing performance, not how many elements you can ever add to a collection.

(Finally, as a side note, I recommend noticing how Vector has effectively been replaced by ArrayList for decades, and how you should really never use it anymore.)

  • Related