📜  Java中的矢量 ensureCapacity() 方法与示例

📅  最后修改于: 2022-05-13 01:54:37.712000             🧑  作者: Mango

Java中的矢量 ensureCapacity() 方法与示例

如有必要, Java.util.Vector类的ensureCapacity()方法会增加此 Vector 实例的容量,以确保它至少可以容纳最小容量参数指定的元素数量。

句法:

public void ensureCapacity(int minCapacity)

参数:此方法将所需的最小容量作为参数。

下面是说明ensureCapacity()方法的示例。

示例 1:

// Java program to demonstrate
// ensureCapacity() method for Integer value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // Creating object of Vector
            Vector
                vector = new Vector();
  
            // adding element to vector
            vector.add(10);
            vector.add(20);
            vector.add(30);
            vector.add(40);
  
            // Print the Vector
            System.out.println("Vector: "
                               + vector);
  
            // ensure that the Vector
            // can hold upto 5000 elements
            // using ensureCapacity() method
            vector.ensureCapacity(5000);
  
            // Print
            System.out.println("Vector can now"
                               + " surely store upto"
                               + " 5000 elements.");
        }
  
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
Vector: [10, 20, 30, 40]
Vector can now surely store upto 5000 elements.

示例 2:

// Java program to demonstrate
// ensureCapacity() method for String value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // Creating object of Vector
            Vector
                vector = new Vector();
  
            // adding element to vector
            vector.add("A");
            vector.add("B");
            vector.add("C");
            vector.add("D");
  
            // Print the Vector
            System.out.println("Vector: "
                               + vector);
  
            // ensure that the Vector
            // can hold upto 400 elements
            // using ensureCapacity() method
            vector.ensureCapacity(400);
  
            // Print
            System.out.println("Vector can now"
                               + " surely store upto"
                               + " 400 elements.");
        }
  
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
Vector: [A, B, C, D]
Vector can now surely store upto 400 elements.