Java ArrayList clear() Method
The clear() method is used to remove all elements from the dynamic array.
The syntax of the clear() method is:
arraylist.clear()
**Note:** arraylist is an object of the ArrayList class.
Parameter Description:
- None
Example
Deleting all elements using ArrayList clear():
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.
clear
(
)
;
System
.
out
.
println
(
"After all clear() method: "
sites
)
;
}
}
The output of the above program is:
网站列表: [Google, Runoob, Taobao]
所有 clear() 方法后: []
In the example above, we created a dynamic array named sites. This dynamic array stores website names.
At the end of the example, we used the clear() method to remove all elements of the dynamic array sites.
clear() vs removeAll() Method
The dynamic array also provides the removeAll() method, which can also remove all elements from the array, as follows:
Example
import
java.util.ArrayList
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a dynamic array
ArrayList
<
Integer
oddNumbers
=
new
ArrayList
<>
(
)
;
// Add elements to the dynamic array
oddNumbers.
add
(
1
)
;
oddNumbers.
add
(
3
)
;
oddNumbers.
add
(
5
)
;
System
.
out
.
println
(
"Odd ArrayList: "
oddNumbers
)
;
// Remove all elements
oddNumbers.
removeAll
(
oddNumbers
)
;
System
.
out
.
println
(
"After using removeAll() method: "
oddNumbers
)
;
}
}
The output of the above program is:
奇数 ArrayList: [1, 3, 5]
使用 removeAll() 方法后: []
In the example above, we created a dynamic array named oddNumbers, then used the removeAll() method to remove all elements from the array.
The removeAll() and clear() methods have the same function. However, the clear() method is used more often than removeAll() because clear() is faster and more efficient than removeAll().
To learn more about removeAll(), please visit Java ArrayList removeAll() Method.
Java ArrayList