Junior — Middle
Millised on Kotlinis saadaval olevad Set-liidese rakendamise viisid ja kuidas nad erinevad?
sobes.tech AI
Vastus AI-lt
In Kotlin, the Set interface is implemented in various ways, which differ in mutability and internal implementation:
- Set — an interface for an immutable (read-only) set. It provides read operations but not modification.
- MutableSet — extends Set and adds methods for modifying the set (adding, removing elements).
Implementations:
- HashSet — based on a hash table, provides fast access and add/remove operations. The order of elements is not guaranteed.
- LinkedHashSet — inherits from HashSet, maintains insertion order of elements.
- SortedSet / TreeSet (via Java) — a set whose elements are sorted by natural order or by a comparator.
Example:
val readOnlySet: Set<Int> = setOf(1, 2, 3)
val mutableSet: MutableSet<Int> = mutableSetOf(1, 2, 3)
mutableSet.add(4) // allowed
// readOnlySet.add(4) // compilation error
Thus, the choice of implementation depends on the requirements for mutability and element order.