![]() |
VOOZH | about |
The retainAll() method of ArrayList class in Java is used to retain only the elements in the list that are contained in the specified collection. It removes all elements from the list that are not in the specified collection.
Example 1: Passing an ArrayList as the Parameter
In this example, we pass an ArrayList as the parameter to the retainAll() method and demonstrate how only the common elements are retained in the target list.
Before retainAll() al1: [pen, pencil, paper] Before retainAll() al2: [pen, paper, books, rubber] After retainAll() al1: [pen, pencil, paper] After retainAll() al2: [pen, paper]
Explanation: In the above example, the retainAll() method keeps only the elements from al2 that are also in al1. Therefore, after the method is applied, al2 contains only the common elements i.e. [pen, paper].
public boolean retainAll(Collection C)
Parameters: c: The collection whose elements should be retained in the ArrayList.
Return Value:
Exceptions:
Example 2: Passing a Collection Other than ArrayList
Here, we pass a HashSet instead of an ArrayList as the parameter. This demonstrates that retainAll() can be used with any collection type.
Before retainAll() s:[paper, ink, pen] Before retainAll() l: [pen, paper, books, rubber, ink] After retainAll() s: [paper, ink, pen] After retainAll() l: [pen, paper, ink]
Explanation: In this case, "s" is a HashSet, and "l" is an ArrayList. After calling retainAll(), "l" retains only the elements that are present in "s", resulting in [pen, paper, ink].
Example 3: Illustrating the error thrown by retainAll() method.
Output:
Hangup (SIGHUP)
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:221)
at java.base/java.util.ArrayList.batchRemove(ArrayList.java:848)
at java.base/java.util.ArrayList.retainAll(ArrayList.java:843)
at GFG.main(GFG.java:26)
Explanation: The above code demonstrates a NullPointerException exception thrown when trying to call the retainAll() method with a null reference (l1). Since l1 is null, trying to perform the operation results in an exception.