Map API ¶The Map_K_V structure has the following methods. Note that its
“subclasses” HashMap_K_V and BTreeMap_K_V each have
the same fields.
Depending on which constructor is used, a Map may or may not have
valid instances of nullValue and isNullValue(V). If one of
these is valid, the other will be too. In some methods below, an error
will be thrown unless nullValue can be returned to indicate an
element is not present. When nullValue is defined for a map
m, the expression m.isNullValue(m[k]) is equivalent to
m.contains(k).
int size()returns the number of distinct keys in the map.
bool empty()returns true iff size() == 0.
bool contains(K key)returns true if key is present as a key in
the map.
V operator [] (K key)returns the value
associated with the element key. If key is not present,
this method either returns nullValue or, if nullValue does not
exist, throws an error. See Bracket operators.
void operator [=] (K key, V value)adds the pair
(key, value) to the map. If a key equivalent to key is
already present, its associated value is replaced (as is the key
itself, but that should rarely matter since the old and new keys are
equivalent). However, if
isNullValue(value) is true, then the assignment instead removes
key from the map if it was already there. See Bracket operators.
void delete(K key)removes key from the map. If key was
not already in the map, an error is thrown. (An alternative that will not
throw an error is to set the value of key to nullValue.)
Iter_K operator iter()returns an iterator over the keys of the map.
It allows the map to be used in range-based for loops, as in
for (K key : m) {<statements>}
If a key is deleted or a new key is inserted, then any iterators created before that change are undermined and may behave unpredictably. The current implementations attempt to throw errors if an iterator is used after being undermined, but this behavior is not guaranteed and might be removed in future versions for performance reasons.
Iterable_K_V pairs()returns an iterable over the key-value pairs. For example,
for (Pair_K_V p : m.pairs()) {
K key = p.k;
V value = p.v;
<statements>
}
K[] keys()returns an array of all the keys. The array is a shallow copy; changes to it will not affect the map (and vice versa), but changes to the entries of the keys will undermine the integrity of the map.
void add(Iterable_K_V other)adds the key-value pairs from other.
Running m.add(o); should be equivalent to running
for (var pr : o) { m[pr.k] = pr.v; }
In addition to these methods, there is also an autounraveled implicit cast from
Map_K_V to Iterable_K. This cast allows a Map_K_V to be
passed as a parameter to utilities like zip or enumerate.