java.util.Vector.clear()


描述

clear()方法被用来去除所有从此向量元素。除非它抛出异常,否则在此调用之后Vector将为空。

声明

以下是java.util.Vector.clear()方法的声明

public void clear()

参数

此方法不接受任何参数作为输入。

返回值

返回类型为void,因此它不返回任何值。

异常

UnsupportedOperationException - 如果Collection不支持clear方法,则抛出此异常。

实例

以下示例显示了java.util.Vector.clear()方法的用法。

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String[] args) {

      // create an empty Vector vec with an initial capacity of 4      
      Vector<Integer> vec = new Vector<Integer>(4);

      // use add() method to add elements in the vector
      vec.add(4);
      vec.add(3);
      vec.add(2);
      vec.add(1);

      // let us print the size of the vector
      System.out.println("Size of the vector after addition :"+vec.size());
      System.out.println("Added numbers are :- ");

      for (Integer number : vec) {         
         System.out.println("Number = " + number);
      }

      // let us clear the vector
      vec.clear();

      // let us print the size of the vector
      System.out.println("Size of the vector after clearing :"+vec.size());       
   }
}

让我们编译并运行上面的程序,这将产生以下结果。调用clear()方法后向量的大小为0。

Size of the vector after addition :4
Added numbers are :-
Number = 4
Number = 3
Number = 2
Number = 1
Size of the vector after clearing :0