如有必要,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.
相關用法
- Java Stack ensureCapacity()用法及代碼示例
- Java StringBuffer ensureCapacity()用法及代碼示例
- Java ArrayList ensureCapacity()用法及代碼示例
- Java StringBuilder ensureCapacity()用法及代碼示例
- Java Vector set()用法及代碼示例
- Java Vector add()用法及代碼示例
- Java Vector contains()用法及代碼示例
- Java Vector get()用法及代碼示例
- Java Vector containsAll()用法及代碼示例
- Java Vector capacity()用法及代碼示例
- Java Vector copyInto()用法及代碼示例
- Java Vector removeAllElements()用法及代碼示例
- Java Vector isEmpty()用法及代碼示例
- Java Vector lastIndexOf()用法及代碼示例
- Java Vector trimToSize()用法及代碼示例
注:本文由純淨天空篩選整理自SandySharma大神的英文原創作品 Vector ensureCapacity() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。