lib/map: document `Map.has_key` and implement it efficienlty
[nit.git] / lib / standard / collection / hash_collection.nit
index cae46fd..cdc7906 100644 (file)
 # You  are  allowed  to  redistribute it and sell it, alone or is a part of
 # another product.
 
-# Introduce Hashmap and Hashset.
+# Introduce `HashMap` and `HashSet`.
 module hash_collection
 
 import array
 
+redef class Map[K, V]
+       # Get a `HashMap[K, V]` as default implementation
+       new do return new HashMap[K, V]
+end
+
 # A HashCollection is an array of HashNode[K] indexed by the K hash value
 private abstract class HashCollection[K]
        type N: HashNode[K]
@@ -230,6 +235,16 @@ class HashMap[K, V]
                end
        end
 
+       redef fun get_or_null(key)
+       do
+               var c = node_at(key)
+               if c == null then
+                       return null
+               else
+                       return c._value
+               end
+       end
+
        redef fun iterator: HashMapIterator[K, V] do return new HashMapIterator[K,V](self)
 
        redef fun length do return _the_length
@@ -259,6 +274,7 @@ class HashMap[K, V]
 
        redef var keys: RemovableCollection[K] = new HashMapKeys[K, V](self)
        redef var values: RemovableCollection[V] = new HashMapValues[K, V](self)
+       redef fun has_key(k) do return node_at(k) != null
 end
 
 # View of the keys of a HashMap
@@ -403,7 +419,7 @@ end
 
 # A `Set` implemented with a hash table.
 # Keys of such a map cannot be null and require a working `hash` method
-class HashSet[E: Object]
+class HashSet[E]
        super Set[E]
        super HashCollection[E]
 
@@ -457,12 +473,12 @@ class HashSet[E: Object]
        redef fun new_set do return new HashSet[E]
 end
 
-private class HashSetNode[E: Object]
+private class HashSetNode[E]
        super HashNode[E]
        redef type N: HashSetNode[E]
 end
 
-private class HashSetIterator[E: Object]
+private class HashSetIterator[E]
        super Iterator[E]
        redef fun is_ok do return _node != null