How to use the HashSet.clear method in Kotlin
Overview
The clear method removes all the elements present in the HashSet object.
Syntax
fun clear()
Parameters
This method doesn’t take any arguments.
Return value
This method doesn’t return any value.
Code
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")}
Explanation
-
Line 3: We create a new
HashSetobject namedset. We use thehashSetOf()method to create an emptyHashSet. -
Lines 6–9: We add four new elements (1,2,3,4) to the
setusing theadd()method. -
Line 13: We use the
clearmethod to remove all the elements present in theset. Thesetbecomes empty after calling theclearmethod.