From: Jean Privat Date: Tue, 4 Mar 2014 17:03:19 +0000 (-0500) Subject: lib/more_collection: MultiHashMap associates new arrays to unknown keys X-Git-Tag: v0.6.5~54^2 X-Git-Url: http://nitlanguage.org lib/more_collection: MultiHashMap associates new arrays to unknown keys Signed-off-by: Jean Privat --- diff --git a/lib/more_collections.nit b/lib/more_collections.nit index aad9f4c..50117cf 100644 --- a/lib/more_collections.nit +++ b/lib/more_collections.nit @@ -16,6 +16,19 @@ module more_collections # Simple way to store an `HashMap[K, Array[V]]` +# +# Unlike standard HashMap, MultiHashMap provides a new +# empty array on the first access on a unknown key. +# +# var m = new MultiHashMap[String, Char] +# assert not m.has_key("four") +# m["four"].add('i') +# m["four"].add('i') +# m["four"].add('i') +# m["four"].add('i') +# assert m.has_key("four") +# assert m["four"] == ['i', 'i', 'i', 'i'] +# assert m["zzz"] == new Array[Char] class MultiHashMap[K: Object, V] super HashMap[K, Array[V]] @@ -30,6 +43,12 @@ class MultiHashMap[K: Object, V] end end + redef fun provide_default_value(key) do + var res = new Array[V] + self[key] = res + return res + end + init do end end