Java教程

Java Vector removeAll()

Java向量类的 removeAll()方法从向量中删除了指定元素中存在的所有元素

语法

以下是 removeAll()方法的声明:
public boolean removeAll(Collection<?> c)

参数

参数 说明 必需/可选
c 它是元素的集合,将从向量中删除。 必需

返回

如果引导程序改变了Vector ,则 removeAll()方法将返回true。

异常

NullPointerException -如果向量包含一个或多个null元素并且指定的集合不支持null元素,或者如果

兼容版本

Java 1.2及更高版本

示例1

import java.util.Vector;
public class VectorRemoveAllExample1 {  
    public static void main(String arg[]) {
      //Create an empty Vec1
        Vector<Integer> vec1 = new Vector<>();
        //Add elements in the Vector1
        vec1.add(1);
        vec1.add(2);
        vec1.add(3);
        vec1.add(4);
        vec1.add(5); 
        //Displaying the Vector elements
        System.out.println("Vector: " + vec1); 
        System.out.println("Removing all the elements"); 
        //use removeAll() method
        vec1.removeAll(vec1);
        //Display the size of the Vector
        System.out.println("Size of the vector: "+vec1.size()); 
        }
}
输出:
Vector: [1, 2, 3, 4, 5]
Removing all the elements
Size of the vector: 0

示例2

import java.util.Vector;
public class VectorRemoveAllExample2 {  
    public static void main(String arg[]) {
      //Create an empty Vec1
        Vector<String> vec1 = new Vector<String>();
        //Add elements in the Vector1
        vec1.add("A");
        vec1.add("B");
        vec1.add("C");
        vec1.add("10");
        vec1.add("20"); 
        //Displaying the Vector1 elements
        System.out.println("Vector: " + vec1); 
        //Create an empty Vec2
        Vector<String> vec2 = new Vector<String>(); 
        //Add elements in the Vector2
        vec2.add("A");
        vec2.add("B");
        vec2.add("C"); 
        //use removeAll() method
        boolean changed = vec1.removeAll(vec2);
        //Print the result
        if (changed)
            System.out.println("Collection removed");
        else
            System.out.println("Collection not removed");
        //Display the final Vector
        System.out.println("final Vector: " + vec1);
        }
}
输出:
Vector: [A, B, C, 10, 20]
Collection removed
final Vector: [10, 20]

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4