Java中的 LinkedTransferQueue retainAll() 方法及示例
Java .util.concurrent.LinkedTransferQueue 的retainAll()方法是Java中的一个内置函数,用于保留此队列中的所有元素,即指定集合和此队列共有的元素。所有其他不常见的元素都从此队列中删除。
句法:
public boolean retainAll(Collection C)
参数:此方法采用参数C ,它是包含要保留在队列中的元素的集合。
返回:如果由于调用 else false 导致队列完全改变,则该方法返回布尔值 true。
异常:此方法引发以下异常:
- ClassCastException :如果此 Queue 的元素的类与 Passed 集合不兼容。
- NullPointerException :如果指定的集合为 Null。
下面的程序说明了 LinkedTransferQueue 类的 retainAll()函数:
方案一:
// Java code to illustrate
// retainAll() method of LinkedTransferQueue
import java.util.concurrent.LinkedTransferQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
// create object of LinkedTransferQueue
LinkedTransferQueue LTQ
= new LinkedTransferQueue();
// Add numbers to end of LinkedTransferQueue
// using add() method
LTQ.add(3);
LTQ.add(6);
LTQ.add(10);
LTQ.add(125);
LTQ.add(205);
// Print the Queue
System.out.println("Linked Transfer Queue : "
+ LTQ);
// Get the ArrayList to be retained
ArrayList arraylist
= new ArrayList();
arraylist.add(10);
arraylist.add(100);
arraylist.add(125);
// Print ArrayList
System.out.println("ArrayList to be retained : "
+ arraylist);
// Retaining elements from the queue
// which are common to arraylist
// using retainAll() method.
LTQ.retainAll(arraylist);
// Prints the Queue
System.out.println("Linked Transfer Queue "
+ "after retaining ArrayList : "
+ LTQ);
}
}
输出:
Linked Transfer Queue : [3, 6, 10, 125, 205]
ArrayList to be retained : [10, 100, 125]
Linked Transfer Queue after retaining ArrayList : [10, 125]
方案二:
// Java code to illustrate
// retainAll() method of LinkedTransferQueue
import java.util.concurrent.LinkedTransferQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws InterruptedException
{
// create object of LinkedTransferQueue
LinkedTransferQueue LTQ
= new LinkedTransferQueue();
// Add numbers to end of LinkedTransferQueue
// using add() method
LTQ.add("GeeksforGeeks");
LTQ.add("Geek");
LTQ.add("Gfg");
LTQ.add("Computer");
LTQ.add("Science");
// Print the Queue
System.out.println("Linked Transfer Queue : "
+ LTQ);
// Get the ArrayList to be retained
ArrayList arraylist
= new ArrayList();
arraylist.add("Gfg");
arraylist.add("Science");
arraylist.add("Computer");
// Print ArrayList
System.out.println("ArrayList to be retained : "
+ arraylist);
// Retaining elements from the queue
// which are common to arraylist
// using retainAll() method.
LTQ.retainAll(arraylist);
// Prints the Queue
System.out.println("Linked Transfer Queue "
+ "after retaining ArrayList : "
+ LTQ);
}
}
输出:
Linked Transfer Queue : [GeeksforGeeks, Geek, Gfg, Computer, Science]
ArrayList to be retained : [Gfg, Science, Computer]
Linked Transfer Queue after retaining ArrayList : [Gfg, Computer, Science]
参考: https://docs.oracle.com/javase/9/docs/api/ Java/util/concurrent/LinkedTransferQueue.html#retainAll-java.util.Collection-