forked from Suryakant-Bharti/Important-Java-Concepts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImmutableSet.kt
37 lines (27 loc) Β· 976 Bytes
/
ImmutableSet.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package algo.datastructures
import algo.search.BinarySearch
/**
* The class represents set of comparables. The values are stored in a sorted array,
* and the inclusion queries perform binary search, taking logarithmic time in the worst case.
*/
class ImmutableSet<T: Comparable<T>>(values: Array<T>): Set<T> {
private val arr: Array<T> = values.sortedArray()
private val bs = BinarySearch<T>() // TODO: remove
override val size: Int
get() = arr.size
override fun contains(element: T): Boolean {
return bs.perform(arr, element) != -1
}
override fun containsAll(elements: Collection<T>): Boolean {
return elements.all { contains(it) }
}
override fun isEmpty(): Boolean {
return size == 0
}
override fun iterator(): Iterator<T> {
return arr.iterator()
}
}
fun <T: Comparable<T>> immutableSetOf(vararg elements: T): ImmutableSet<out T> {
return ImmutableSet(elements.copyOf())
}