📜  Java中的向量clear()方法

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

Java中的向量clear()方法

Java.util.Vector.clear()方法用于从 Vector 中删除所有元素。使用 clear() 方法只会清除向量中的所有元素,不会删除向量。换句话说,我们可以说 clear() 方法仅用于清空现有向量。

句法:

Vector.clear()

参数:该方法不带任何参数

返回值:该函数不返回任何值。

下面的程序说明了Java.util.Vector.clear() 方法。

示例 1:

// Java code to illustrate clear()
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
        // Creating an empty Vector
        Vector vt = new Vector();
  
        // Use add() method to add elements into the Vector
        vt.add("Welcome");
        vt.add("To");
        vt.add("Geeks");
        vt.add("4");
        vt.add("Geeks");
  
        // Displaying the Vector
        System.out.println("Vector: " + vt);
  
        // Clearing the Vector using clear() method
        vt.clear();
  
        // Displaying the final vector after clearing;
        System.out.println("The final Vector: " + vt);
    }
}
输出:
Vector: [Welcome, To, Geeks, 4, Geeks]
The final Vector: []

示例 2:

// Java code to illustrate clear()
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
        // Creating an empty Vector
        Vector vt = new Vector();
  
        // Use add() method to add elements into the Queue
        vt.add(10);
        vt.add(15);
        vt.add(30);
        vt.add(20);
        vt.add(5);
  
        // Displaying the Vector
        System.out.println("Vector: " + vt);
  
        // Clearing the Vector using clear() method
        vt.clear();
  
        // Displaying the final vector after clearing;
        System.out.println("The final Vector: " + vt);
    }
}
输出:
Vector: [10, 15, 30, 20, 5]
The final Vector: []