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


Java Vector trimToSize()用法及代碼示例


Java中的Vector的trimToSize()方法將Vector實例的容量調整為Vector的當前大小。此方法用於將Vector實例修剪為包含的元素數量。

用法:

trimToSize()

參數:它不接受任何參數。


返回值:它不返回任何值。它將Vector實例的容量調整為它包含的元素數。

以下示例程序旨在說明trimTosize()方法:

示例1:

// Java code to demonstrate the working of 
// trimTosize() method in Vector 
  
import java.util.Vector; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // creating an Empty Integer Vector 
        Vector<Integer> vector 
            = new Vector<Integer>(9); 
  
        // using add(), add 5 values 
        vector.add(2); 
        vector.add(4); 
        vector.add(5); 
        vector.add(6); 
        vector.add(11); 
  
        // Displaying the Vector 
        System.out.println("Initial Vector is: " + vector); 
  
        // Displaying the Vector 
        System.out.println("Initial size is: " + vector.size()); 
  
        // trims the size to the number of elements 
        vector.trimToSize(); 
  
        // Displaying the Vector 
        System.out.println("Size after using trimToSize(): "
                           + vector.size()); 
    } 
}
輸出:
Initial Vector is: [2, 4, 5, 6, 11]
Initial size is: 5
Size after using trimToSize(): 5

示例2:

// Java code to demonstrate the working of 
// trimTosize() method in Vector 
  
import java.util.Vector; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // creating vector type object 
        Vector<String> vector = new Vector<String>(); 
  
        // Inserting elements into the table 
        vector.add("Geeks"); 
        vector.add("4"); 
        vector.add("Geeks"); 
        vector.add("Welcomes"); 
        vector.add("You"); 
  
        // Displaying the Vector 
        System.out.println("Initial Vector is: " + vector); 
  
        // Displaying the Vector 
        System.out.println("Initial size is: " + vector.size()); 
  
        // trims the size to the number of elements 
        vector.trimToSize(); 
  
        // Displaying the Vector 
        System.out.println("Size after using trimToSize(): "
                           + vector.size()); 
    } 
}
輸出:
Initial Vector is: [Geeks, 4, Geeks, Welcomes, You]
Initial size is: 5
Size after using trimToSize(): 5


相關用法


注:本文由純淨天空篩選整理自ankit15697大神的英文原創作品 Vector trimToSize() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。