当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Vector 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<Integer> 
            Vector<Integer> 
                vector = new Vector<Integer>(); 
  
            // 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<Integer> 
            Vector<String> 
                vector = new Vector<String>(); 
  
            // 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.


相关用法


注:本文由纯净天空筛选整理自SandySharma大神的英文原创作品 Vector ensureCapacity() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。