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 elements
var set: HashSet<Int> = hashSetOf<Int>()
// add four entries
set.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 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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources