Java教程

Java Vector keepAll()

Java Vector类的 retainAll()方法用于仅保留Vector 中包含的元素在指定的集合中。换句话说,它将删除此向量中所有未包含在指定集合中的元素。

语法

以下是 retainAll( )方法:
public boolean retainAll(Collection<?> c)

参数

参数 说明 必需/可选
c 它是元素的集合,这些元素将保留在此向量中,所有其他元素都将被删除。 必需

返回

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

异常

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

兼容版本

Java 1.2及更高版本

示例1

import java.util.Vector;
public class VectorRetainAllExample1 {  
    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(2); 
        //Create an empty Vec2
        Vector<Integer> vec2 = new Vector<>();
        //Add elements in the Vector2
        vec2.add(2);
        vec2.add(3); 
        //Displaying the Vector elements      
        System.out.println("Values in vector :" +vec1);
        //use retainAll() method
        vec1.retainAll(vec2);
        System.out.println("Values in vector :" +vec1);
      }
}
输出:
Values in vector :[1, 2, 3, 4, 2]
Values in vector :[2, 3, 2]

示例2

import java.util.Vector;
public class VectorRetainAllExample2 {  
    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 retainAll() method
        boolean changed = vec1.retainAll(vec2);
        //Print the result
        if (changed)
            System.out.println("Collection retained");
        else
            System.out.println("Collection not retained");
        //Display the final Vector
        System.out.println("final Vector: " + vec1);
      }
}
输出:
Vector: [A, B, C, 10, 20]
Collection retained
final Vector: [A, B, C]

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