Java中Vector的大小和容量之间有什么区别?
向量的大小表示向量中组件的数量。向量的容量表示向量可以容纳的最大元素数。
例:
import java.util.*;public class VectorDemo { public static void main(String args[]) { Vector v = new Vector(3, 2); System.out.println("Initial size: " + v.size()); System.out.println("Initial capacity: " + v.capacity()); v.addElement(new Integer(1)); v.addElement(new Integer(2)); v.addElement(new Integer(3)); v.addElement(new Integer(4)); System.out.println("Capacity after four additions: " + v.capacity()); v.addElement(new Double(5.45)); System.out.println("Current capacity: " + v.capacity()); v.addElement(new Double(6.08)); v.addElement(new Integer(7)); System.out.println("Current capacity: " + v.capacity()); v.addElement(new Float(9.4)); v.addElement(new Integer(10)); System.out.println("Current capacity: " + v.capacity()); v.addElement(new Integer(11)); v.addElement(new Integer(12)); System.out.println("First element: " + (Integer)v.firstElement()); System.out.println("Last element: " + (Integer)v.lastElement()); if(v.contains(new Integer(3))) System.out.println("Vector contains 3."); Enumeration vEnum = v.elements(); System.out.println("\nElements in vector:"); while(vEnum.hasMoreElements()) System.out.print(vEnum.nextElement() + " "); System.out.println(); }}
输出:
Initial size: 0Initial capacity: 3Capacity after four additions: 5Current capacity: 5Current capacity: 7Current capacity: 9First element: 1Last element: 12Vector contains 3.Elements in vector:1 2 3 4 5.45 6.08 7 9.4 10 11 12
以上是 Java中Vector的大小和容量之间有什么区别? 的全部内容, 来源链接: utcz.com/z/343536.html