lib/more_collection: MultiHashMap associates new arrays to unknown keys
authorJean Privat <jean@pryen.org>
Tue, 4 Mar 2014 17:03:19 +0000 (12:03 -0500)
committerJean Privat <jean@pryen.org>
Wed, 5 Mar 2014 15:32:49 +0000 (10:32 -0500)
Signed-off-by: Jean Privat <jean@pryen.org>

lib/more_collections.nit

index aad9f4c..50117cf 100644 (file)
 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