Sobes.tech
Junior

What is capacity in the context of Java?

sobes.tech AI

Answer from AI

Capacity in the context of Java most often refers to the size of an internal data structure, such as an array, used to store elements in collections like ArrayList, Vector, or HashMap. It is the maximum number of elements that the collection can hold without needing to recreate and copy the internal array into a larger one.

  • Initial capacity: The initial size of the internal array when creating the collection.
  • Current capacity: The current size of the internal array. It can be larger than the actual number of elements (size), but not smaller.
  • Resizing capacity: When the number of elements reaches the current capacity, the collection automatically increases the size of the internal array (usually by a certain factor, for example, 1.5 times for ArrayList), to accommodate new elements. This process can be time-consuming and resource-intensive.

Managing capacity can affect performance:

  • Too small an initial capacity leads to frequent resizing, which reduces performance when adding a large number of elements.
  • Too large an initial capacity can lead to inefficient memory usage if the collection remains half-empty.

Example for ArrayList:

// Creates an ArrayList with default initial capacity (usually 10)
List<String> defaultCapacityList = new ArrayList<>();

// Creates an ArrayList with initial capacity of 50
List<String> customCapacityList = new ArrayList<>(50);

// Increases capacity if the current capacity is insufficient
for (int i = 0; i < 100; i++) {
    defaultCapacityList.add("Element " + i); // May trigger multiple resizes
}

// The ensureCapacity() method allows explicitly increasing capacity in advance
defaultCapacityList.ensureCapacity(200);