Java ArrayList removeAll() Method
removeAll() method is used to delete dynamic array elements that exist in a specified collection.
The syntax of the removeAll() method is:
arraylist.removeAll(Collection c);
**Note:** arraylist is an object of the ArrayList class.
Parameter Description:
- c - the collection of elements to be deleted from the dynamic array list
Return Value
Returns true if elements are successfully deleted from the dynamic array.
If the element class present in the dynamic array is incompatible with the element class of the specified collection, a ClassCastException is thrown.
If the dynamic array contains a null element and the specified collection does not allow null elements, a NullPointerException is thrown.
Example
Deleting all elements from the dynamic array list:
Example
import
java.util.ArrayList
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create an array
ArrayList
<
String
sites
=
new
ArrayList
<>
(
)
;
sites.
add
(
"Google"
)
;
sites.
add
(
"Runoob"
)
;
sites.
add
(
"Taobao"
)
;
System
.
out
.
println
(
"Website list: "
sites
)
;
// Remove all elements
sites.
removeAll
(
sites
)
;
System
.
out
.
println
(
"After all removeAll() method: "
sites
)
;
}
}
The output of the above program is:
网站列表: [Google, Runoob, Taobao]
所有 removeAll() 方法后: []
In the example above, we created a dynamic array named sites. This dynamic array stores website names.
Note this line:
sites.removeAll(sites);
sites is passed as the parameter of the removeAll() method.
Note: clear() is the best method to delete all elements from the dynamic array. To learn more, please visit Java ArrayList clear().
Java ArrayList