當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java java.util.Vector.ensureCapacity()用法及代碼示例


描述

這個ensureCapacity(int minCapacity)方法用於在必要時增加此向量的容量。這是為了確保該向量至少可以容納由minimum capacity argument.如果這個向量的當前容量小於minCapacity,然後通過用更大的數組替換其保留在字段 elementData 中的內部數據數組來增加其容量。新數據數組的大小將是old size plus capacityIncrement.如果 capacityIncrement 的值小於或等於零,那麽新容量將是舊容量的兩倍。但如果這個新大小仍然小於 minCapacity,那麽新容量將是 minCapacity。

聲明

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

public void ensureCapacity(int minCapacity)

參數

minCapacity─ 這是所需的最小容量。

返回值

它返回void。

異常

NA

示例

下麵的例子展示了 java.util.Vector.ensureCapacity() 方法的用法。

package com.tutorialspoint;

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

相關用法


注:本文由純淨天空篩選整理自 java.util.Vector.ensureCapacity() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。