Junior — Middle
What data structure is best suited for storing unique elements without duplicates?
sobes.tech AI
Answer from AI
To store unique elements without duplicates, it is best to use a data structure called "set" (Set). In Android (Java/Kotlin), this can be HashSet or LinkedHashSet.
A set automatically ensures the uniqueness of elements and allows efficient checking for the presence of an element, as well as adding and removing it.
Example in Kotlin:
val uniqueItems = mutableSetOf<String>()
uniqueItems.add("apple")
uniqueItems.add("banana")
uniqueItems.add("apple") // will not be added again
println(uniqueItems) // Outputs: [apple, banana]