HashMap<K, V>.from constructor
HashMap<K, V>.from (
- Map<
K, V> map
Creates a hash map from an existing map.
This is a factory constructor that creates a new hash map from an existing map.
A custom implementation of a hash map that implements the Map<K, V>
interface.
This map uses open addressing with chaining to resolve hash collisions.
Each bucket holds a list of _HashMapEntry<K, V>
objects, allowing multiple entries
to exist in the same bucket if they hash to the same index.
It supports automatic resizing when the load factor exceeds 0.75
, ensuring
performance remains optimal as the number of entries grows.
This is useful for educational purposes or when custom behavior is required
beyond what dart:collection
offers.
⚙️ Internal Design:
- Backed by an array of lists:
List<List<_HashMapEntry<K, V>>?> _buckets
- On collision: new entries are appended to the appropriate list
- Resize logic doubles capacity when load factor exceeds the threshold
📦 Example Usage:
final map = HashMap<String, int>();
map['apple'] = 3;
map['banana'] = 5;
print(map['apple']); // 3
print(map.containsKey('banana')); // true
print(map.length); // 2
Implementation
factory HashMap.from(Map<K, V> map) {
final result = HashMap<K, V>();
map.forEach((key, value) {
result[key] = value;
});
return result;
}