📜  Java中的矢量 trimToSize() 方法与示例

📅  最后修改于: 2022-05-13 01:55:31.990000             🧑  作者: Mango

Java中的矢量 trimToSize() 方法与示例

Java中VectortrimToSize()方法将 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 vector
            = new Vector(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 vector = new Vector();
  
        // 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