目录

void ensureCapacity(int minCapacity)

描述 (Description)

如果需要, ensureCapacity(int minCapacity)方法用于增加此向量的容量。这是为了确保向量至少可以容纳由minimum capacity argument指定的组件数。如果此向量的当前容量为小于minCapacity ,然后通过将其内部数据数组(保留在字段elementData中)替换为较大的数据来增加其容量。 新数据数组的old size plus capacityIncrement将是old size plus capacityIncrement 。如果old size plus capacityIncrement的值小于或等于零,那么新容量将是旧容量的两倍。但是如果这个新大小仍然小于minCapacity,那么新的容量将是minCapacity。

声明 (Declaration)

以下是java.util.Vector.ensureCapacity()方法的声明

public void ensureCapacity(int minCapacity)

参数 (Parameters)

minCapacity - 这是所需的最小容量。

返回值 (Return Value)

它返回void。

异常 (Exception)

NA

例子 (Example)

以下示例显示了java.util.Vector.ensureCapacity()方法的用法。

package com.iowiki;
import java.util.Vector;
public class VectorDemo {
   public static void main(String args[]) {
      // create a vector of initial capacity 5 
      Vector vec = new Vector(5);
      for (int i = 0; i < 10; i++) {
         vec.add(0,i);
      }
      System.out.println("Content of the vector: "+vec);
      System.out.println("Size of the vector: "+vec.size());  
      // ensure the capacity of the vector and add elements
      vec.ensureCapacity(40);
      for (int i = 0; i < 10; i++) {
         vec.add(0,i);
      }    
      System.out.println("Content of the vector after increasing the size: "+vec);
      System.out.println("Size of the vector after increase: "+vec.size());
   }    
}

让我们编译并运行上面的程序,这将产生以下结果。

Content of the vector: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Size of the vector: 10
Content of the vector after increasing the size: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Size of the vector after increase: 20
↑回到顶部↑
WIKI教程 @2018