The clear
method removes all the elements present in the HashSet
object.
fun clear()
This method doesn’t take any arguments.
This method doesn’t return any value.
The code below demonstrates the use of the clear
method to remove all elements present in the HashSet
:
fun main() {//create a new HashSet which can have integer type as elementsvar set: HashSet<Int> = hashSetOf<Int>()// add four entriesset.add(1)set.add(2)set.add(3)set.add(4)println("\nThe set is : $set")set.clear();println("\n After calling clear method The set is : $set")}
Line 3: We create a new HashSet
object named set
. We use the hashSetOf()
method to create an empty HashSet
.
Lines 6–9: We add four new elements (1,2,3,4) to the set
using the add()
method.
Line 13: We use the clear
method to remove all the elements present in the set
. The set
becomes empty after calling the clear
method.