Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

How to use the HashSet.clear method in Kotlin

Programming Bytes

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")

}
Using the clear method

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.

RELATED TAGS

kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring