Java教程

Java Vector trimToSize()

Java Vector类的 trimToSize()方法用于将Vector 的容量修整为Vector 的目前的规模。应用程序可以使用此操作来最小化向量的存储。

语法

以下是 trimToSize()方法的声明:
public void trimToSize()

参数

此方法不接受任何参数。

返回

trimToSize()方法不会返回任何内容。

异常

NA

兼容版本
Java 1.2及更高版本

示例1

import java.util.*;
public class VectorTrimToSizeExample1 {  
  public static void main(String arg[]) { 
      //Create an empty vector 
      Vector<Integer> vec = new Vector<>(8);
      //Add elements in the vector
      vec.add(1);
      vec.add(2);
      vec.add(3);
      vec.add(4);
      vec.add(5);    
      //Trims the size to the number of elements
          vec.trimToSize(); 
          System.out.println("The elements of a vector are:");
          //Displaying all the elements
          for (Integer number : vec) {
             System.out.println("Number = " + number);
          }           
      }
}
输出:
The elements of a vector are:
Number = 1
Number = 2
Number = 3
Number = 4
Number = 5

示例2

import java.util.*;
public class VectorTrimToSizeExample2 {  
  public static void main(String arg[]) { 
      //Create an empty vector
      Vector < String > colors = new Vector < String > (9);
      //Add elements in the vector
          colors.add("White");
          colors.add("Green");
          colors.add("Black");
          colors.add("Pink"); 
          //Prints size of the vector
          System.out.println("The initial size of the vector: "+colors.capacity());
      //Trims the size to the number of elements
          colors.trimToSize(); 
          System.out.println("The elements of a vector are:");
          //Displaying all the elements
          for (String strcolor : colors) {
              System.out.println(" " + strcolor);
          }  
          //Prints size of the vector
          System.out.println("Size of the vector after trimToSize(): " +colors.capacity());
      }
}
输出:
The initial size of the vector: 9
The elements of a vector are:
 White
 Green
 Black
 Pink
Size of the vector after trimToSize(): 4

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