![]() |
Kotlin HashSet is a generic unordered collection of elements and it does not contain duplicate elements. It implements the set interface. hashSetOf() is a function that returns a mutable hashSet, which can be both read and written. The HashSet class store all the elements using the hashing mechanism. Syntax: fun <T> hashSetOf(vararg elements: T): HashSet<T> It returns a new HashSet with the given elements but does not guarantee the order sequence specified at the storing time. Example of hashSetOf() Kotlin
Output: [1, 2, 3] [Geeks, for, geeks] Adding and removing elements in hashset –
Kotlin program of using the add() and remove() method: Kotlin
Output: [] [1, 2, 4, 5, 6] [1, 4, 5, 6] Traversal in hashSet-We can traverse a hashSet using an iterator in a loop. Kotlin
Output: 1 2 3 5 HashSet Indexing –Using index functions indexOf() , lastIndexOf() we can get the index of the specified element. And we can also find the elements at some specific index using elementAt() function. Kotlin program of using index – Kotlin
Output: The element at index 2 is: Malinga The index of element is: 4 The last index of element is: 0 contains() and containsAll() functions –Both the methods are used to check whether an element is present in the Hashset or not? Kotlin
Output: The set contains the element Rohit or not? true The set contains the element 5 or not? false The set contains the given elements or not? false Checking equality of empty hash sets and use of isEmpty() functions –fun <T> hashSetOf(): hashSet<T> This syntax returns an empty hash set of a specific type. Kotlin
Output : seta.isEmpty() is true seta == setb is true hashSetOf() is a function in Kotlin that creates a new hash set. A hash set is an unordered collection of unique elements that provides constant time performance for adding, removing, and checking the presence of an element. Here’s an example of using hashSetOf() to create a set of integers: Kotlin
Output: Numbers: [1, 3, 4] In this example, we create a new hash set of integers using the hashSetOf() function and add three elements to it: 1, 2, and 3. We then add the element 4 to the set and remove 2 from the set. Finally, we check if the set contains the element 5 using the contains() function and print the result to the console. Advantages of hashSetOf():
Disadvantages of hashSetOf():
|
Reffered: https://www.geeksforgeeks.org
Kotlin |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 7 |