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 and get methods for setting/ getting items
      • myMap.put(K, V)
      • MyObject V = myMap.get(K)
    • C#’s Dictionary uses [] indexing for setting/getting items
      • myDictionary[K] = V
      • MyObject V= myDictionary[K]
  • null Keys
    • Java’s HashMap allows null keys (One Null key and n number of null values)
    • C#’s Dictionary throws an ArgumentNullException if you try to add a null key
  • 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 the Add method, it will throw an ArgumentException. To overwrite the old Key with new Key, we should use  [] indexing.
  • 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 a KeyNotFoundException. You can use the TryGetValue method instead of the [] indexing to avoid this:
      MyObject V= null;
      if (!myDictionary.TryGetValue(K, V)) { /* Key not exists */ }

To avoid above two issues, we can use  containsKey method available in both before put or get.





Click Here to Leave a Comment Below 0 comments