Java HashMap equivalent in C#
HashMap maintains key and value pairs and often denoted as HashMap<Key, Value> or HashMap<K, V>. HashMap implements Map interface. HashMap is similar to Hashtable with two exceptions – HashMap methods are unsynchornized and it allows null key and null values unlike Hashtable. It is used for maintaining key and value mapping.
What is equivalent to HashMap in C#?
Dictionary is close to HashMap but not equivalent. System.Collections.Generic.Dictionary
implements the System.Collections.Generic.IDictionary
interface .
Some of the differences between Dictionary and HashMap are
- Adding / Retrieving
- Java’s HashMap has the
put
andget
methods for setting/ getting itemsmyMap.put(K, V)
MyObject V = myMap.get(K)
- C#’s Dictionary uses
[]
indexing for setting/getting itemsmyDictionary[K] = V
MyObject V= myDictionary[K]
- Java’s HashMap has the
null
Keys- Java’s
HashMap
allows null keys (One Null key and n number of null values) - C#’s
Dictionary
throws anArgumentNullException
if you try to add a null key
- Java’s
- Duplicate Keys
- Java’s
HashMap
will replace the old value with the new value. - C#’s
Dictionary
will replace the old value with the new one if you use[]
indexing. If you use theAdd
method, it will throw anArgumentException
. To overwrite the old Key with new Key, we should use[]
indexing.
- Java’s
- Trying to get a non-existent key
- Java’s
HashMap
returns null if the map contains no mapping for the key. - C#’s
Dictionary
will throw aKeyNotFoundException
. You can use theTryGetValue
method instead of the[]
indexing to avoid this:
MyObject V= null;
if (!myDictionary.TryGetValue(K, V)) { /* Key not exists */ }
- Java’s
To avoid above two issues, we can use containsKey
method available in both before put or get.
References
1.HashMap