YouTip LogoYouTip

Java Vector Capacity

## Java Vector capacity() Method The `capacity()` method is a built-in method provided by the `java.util.Vector` class in Java. It returns the current capacity of the vector. The capacity represents the total number of elements the vector can hold without needing to reallocate its internal storage array. --- ### Syntax ```java public int capacity() ``` ### Return Value * **Type:** `int` * **Description:** Returns the current capacity (the length of the internal data buffer) of the `Vector` object. --- ## Basic Usage ### Code Example ```java import java.util.Vector; public class VectorCapacityExample { public static void main(String[] args) { // Create a Vector with an initial capacity of 10 Vector fruits = new Vector<>(10); // Add elements to the Vector fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Retrieve the current capacity int currentCapacity = fruits.capacity(); System.out.println("Current Vector Capacity: " + currentCapacity); } } ``` ### Output ```text Current Vector Capacity: 10 ``` --- ## Deep Dive: Capacity vs. Size It is crucial to distinguish between a vector's **capacity** and its **size**: * **Capacity (`capacity()`)**: The total size of the internal array. It represents how many elements the vector can hold before it must grow. * **Size (`size()`)**: The actual number of elements currently stored in the vector. ```java import java.util.Vector; public class CapacityVsSizeExample { public static void main(String[] args) { Vector numbers = new Vector<>(5); // Initial capacity of 5 numbers.add(1); numbers.add(2); System.out.println("Capacity: " + numbers.capacity()); // Outputs 5 System.out.println("Size: " + numbers.size()); // Outputs 2 } } ``` --- ## Automatic Capacity Growth Mechanism When the number of elements in a `Vector` exceeds its current capacity, the vector automatically increases its capacity. * **Default Behavior:** If no capacity increment is specified, the vector doubles its capacity when it runs out of space. * **Custom Increment:** You can specify a capacity increment when initializing the vector. ### Example: Custom Capacity Increment ```java import java.util.Vector; public class VectorGrowthExample { public static void main(String[] args) { // Create a Vector with an initial capacity of 3 and a capacity increment of 2 Vector vec = new Vector<>(3, 2); System.out.println("Initial Capacity: " + vec.capacity()); // Outputs 3 vec.add(1); vec.add(2); vec.add(3); // Adding the 4th element exceeds the initial capacity of 3, triggering expansion vec.add(4); System.out.println("Capacity After Growth: " + vec.capacity()); // Outputs 5 (3 + 2) } } ``` --- ## Best Practices 1. **Set an Appropriate Initial Capacity:** If you can estimate the number of elements your vector will hold, initialize it with that capacity. This minimizes costly array reallocation and copying operations. 2. **Avoid Frequent Resizing:** Frequent resizing degrades performance, especially when dealing with large datasets. 3. **Use `trimToSize()` to Save Memory:** If you have finished adding elements to a vector and want to release unused memory, call `trimToSize()`. This shrinks the capacity of the vector down to its current size. ```java Vector names = new Vector<>(100); // Add elements... names.trimToSize(); // Reduces capacity to match the current size ``` --- ## Frequently Asked Questions ### Q1: What is the difference between `capacity()` and `size()`? * `capacity()` returns the total allocated space in the internal array. * `size()` returns the actual number of elements currently stored in the vector. ### Q2: Why is my Vector's capacity much larger than the number of elements? This is due to the automatic growth mechanism. When a vector needs to expand, it allocates extra space (either doubling or adding the specified increment) to prevent having to resize again on the very next insertion. This can temporarily result in a capacity that is much larger than the actual element count. ### Q3: How can I reduce the capacity of a Vector? You can use the `trimToSize()` method to trim the capacity down to the vector's current size: ```java vector.trimToSize(); ``` --- ## Summary The `capacity()` method is essential for monitoring and optimizing memory usage in Java `Vector` collections. By understanding and managing vector capacity, you can write more performant and memory-efficient Java applications. Always remember: **capacity** is the allocated storage limit, while **size** is the active element count.
← Java Vector CloneJava Vector Addallint Index Co β†’