patterncsharpCritical
C# Java HashMap equivalent
Viewed 0 times
equivalenthashmapjava
Problem
Coming from a Java world into a C# one is there a HashMap equivalent? If not what would you recommend?
Solution
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
putandgetmethods for setting/getting items
myMap.put(key, value)
MyObject value = myMap.get(key)
- C#'s Dictionary uses
[]indexing for setting/getting items
myDictionary[key] = value
MyObject value = myDictionary[key]
nullkeys
- Java's
HashMapallows null keys
- .NET's
Dictionarythrows anArgumentNullExceptionif you try to add a null key
- Adding a duplicate key
- Java's
HashMapwill replace the existing value with the new one.
- .NET's
Dictionarywill replace the existing value with the new one if you use[]indexing. If you use theAddmethod, it will instead throw anArgumentException.
- Attempting to get a non-existent key
- Java's
HashMapwill return null.
- .NET's
Dictionarywill throw aKeyNotFoundException. You can use theTryGetValuemethod instead of the[]indexing to avoid this:
MyObject value = null;
if (!myDictionary.TryGetValue(key, out value)) { / key doesn't exist / }Dictionary's has a ContainsKey method that can help deal with the previous two problems.Context
Stack Overflow Q#1273139, score: 677
Revisions (0)
No revisions yet.