HashSet
import "std/collections" (included in import "std") · namespace std.collections
HashSet<T> holds each value at most once, with O(1) average add, contains and remove. Elements can be any type HashMap accepts as a key. Iteration order is not defined; use Set to keep insertion order.
grav
import "std"
fn main() {
let a: HashSet<int> = [1, 2, 3, 4]
let b: HashSet<int> = [3, 4, 5]
print(a.add(2)) // already there
print(a.contains(3))
let both = a.intersect(b).toArray()
Sort.sort(both)
print(both)
let all = a.union(b).toArray()
Sort.sort(all)
print(all)
let onlyA = a.difference(b).toArray()
Sort.sort(onlyA)
print(onlyA)
print(b.isSubsetOf(a))
}false
true
[3, 4]
[1, 2, 3, 4, 5]
[1, 2]
falseunion, intersect and difference return new sets.
API
class HashSet<T> implements Iterable<T>
Constructors
new HashSet()
Methods
fn add(item: T) -> bool— Addsitemunless present; reports whether it was added.fn addAll(items: Array<T>)— Adds every element of an array.fn contains(item: T) -> bool— Whether the set hasitem.fn remove(item: T) -> bool— Removesitem; whether it was there.fn size() -> int— The number of elements.fn length() -> int— The number of elements (same as size()).fn isEmpty() -> bool— Whether the set is empty.fn clear()— Removes every element.fn toString() -> string— As text: {1, 2, 3} (strings in quotes).fn toArray() -> Array<T>— The elements as a new Array (in no particular order).fn iterator() -> HashKeyIterator<T, bool>— Walks the elements (in no particular order): whatfor (x in set)uses.fn forEach(f: fn(T))— Calls f on each element (in no particular order).fn union(other: HashSet<T>) -> HashSet<T>— A new set with the elements of both sets.fn intersect(other: HashSet<T>) -> HashSet<T>— A new set with the elements in both sets.fn difference(other: HashSet<T>) -> HashSet<T>— A new set with the elements of this set that are not inother.fn isSubsetOf(other: HashSet<T>) -> bool— Whether every element of this set is inother.