Java教程

Java Vector Capacity()

Java Vector 类的 capacity()方法用于获取当前

语法:

以下是 capacity()方法的声明:
public int capacity()

参数:

此方法不接受任何参数。

返回:

此方法返回

例外:

NA

兼容版本:

Java 1.2及更高版本

示例1:

import java.util.Vector;
public class VectorCapacityExample1 {  
    public static void main(String arg[]) {
        //Create an empty Vector with initial capacity of 5      
        Vector<Integer> vecObject = new Vector<Integer>(5);
        //Add values in the vector
        vecObject.add(3);
        vecObject.add(5);
        vecObject.add(2);
        vecObject.add(4);
        vecObject.add(1);
          System.out.println("Current capacity of Vector is: "+vecObject.capacity());        
            }
}
输出:
Current capacity of Vector is: 5

示例2:

import java.util.Vector;
public class VectorCapacityExample2 {  
    public static void main(String arg[]) {
        //Create an empty Vector with an initial capacity of 3      
          Vector<String> vc = new Vector<>(3);
          //Add elements in the vector
          vc.add("A");
          vc.add("B");
          vc.add("C");         
          //Print all the elements of a Vector
          System.out.println("Elements of Vector are: "+vc);           
          System.out.println("Current capacity of Vector: "+vc.capacity());
          //Add new element
          vc.add("lidihuo");
          //After addition, print all the elements again 
          System.out.println("Elements after addition: "+vc);          
          System.out.println("Current capacity of Vector after modification: "+vc.capacity());
            }
}
输出:
Elements of Vector are: [A, B, C]
Current capacity of Vector: 3
Elements after addition: [A, B, C, lidihuo]
Current capacity of Vector after modification: 6

示例3:

import java.util.Vector;
public class VectorCapacityExample3 {  
    public static void main(String arg[]) {
        //Create an empty Vector    
          Vector<String> vc = new Vector<>();
          //Add elements in the vector
          vc.add("A");
          vc.add("B");
          vc.add("C");                 
          System.out.println("default capacity of Vector: "+vc.capacity());
            }
}
输出:
default capacity of Vector: 10

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4