Coming from a Java world into a C# one is there a HashMap equivalent? If not what would you recommend?
Advertisement
Answer
Dictionary
is probably the closest. System.Collections.Generic.Dictionary
implements the System.Collections.Generic.IDictionary
interface (which is similar to Java’s Map
interface).
Some notable differences that you should be aware of:
- Adding/Getting items
- Java’s HashMap has the
put
andget
methods for setting/getting itemsmyMap.put(key, value)
MyObject value = myMap.get(key)
- C#’s Dictionary uses
[]
indexing for setting/getting itemsmyDictionary[key] = value
MyObject value = myDictionary[key]
- Java’s HashMap has the
null
keys- Java’s
HashMap
allows null keys - .NET’s
Dictionary
throws anArgumentNullException
if you try to add a null key
- Java’s
- Adding a duplicate key
- Java’s
HashMap
will replace the existing value with the new one. - .NET’s
Dictionary
will replace the existing value with the new one if you use[]
indexing. If you use theAdd
method, it will instead throw anArgumentException
.
- Java’s
- Attempting to get a non-existent key
- Java’s
HashMap
will return null. - .NET’s
Dictionary
will throw aKeyNotFoundException
. You can use theTryGetValue
method instead of the[]
indexing to avoid this:
MyObject value = null; if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }
- Java’s
Dictionary
‘s has a ContainsKey
method that can help deal with the previous two problems.