Home » Java ArrayList retainAll() method with Examples

Java ArrayList retainAll() method with Examples

by Online Tutorials Library

Java ArrayList retainAll() method

The retainAll () method of Java ArrayList class keeps only elements in the original list that are contained in the specified collection. In other words, it replaces the original list with the specified list.

Syntax:

Parameter:

“c”: is the Collection that contains elements to be retained in this list.

Return:

Return “true”: if the collection “c” has been retained successfully in the original list.

Exception:

java.lang.ClassCastException: if the class of an element of this list is incompatible with the specified collection.

java.lang.NullPointerException: If the specified collection “c” contains null element and the specified collection does not permit null elements, or the specified collection is null.

Example 1

Test it Now

Output:

[10]  [1, 2, 3]  true  [10]  

Example 2

Test it Now

Output:

null  [1, 2]  

Example 3

Test it Now

Output:

[2, null]  [1, 3]  true  []  

Next TopicJava ArrayList

You may also like