当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。