Expand the capacity of a list to accommodate 15 items.
import public |
The ensureCapacity() method boosts the list’s capacity to a specified level, preemptively expanding it if required.
Although it doesn’t visibly alter the list, it enhances code efficiency.
When methods like add() and addAll() are invoked, insufficient capacity prompts additional space allocation, incurring additional processing time. Hence, ensuring adequate capacity beforehand optimizes performance by minimizing such overhead during add() calls.
If you have an estimate of the number of items you’ll add, using ensureCapacity() enables you to expand the list’s capacity in a single operation, optimizing performance for multiple add() calls.
public |
Parameter |
Description |
capacity |
Mandatory. Indicates the desired capacity of the list, defining the number of items it should be capable of holding. |