Hash maps, sometimes called dictionary or table, are known as unordered maps in C++. The C++ standard library's implementation of hash map is called std::unordered_map .
Therefore, in C++, std::unordered_map is the alternate name for the HashMap, but another map uses the key-value pair concept, the std::map .
The equivalent of HashMap in C# is Dictionary that is used as a collection of key-value pair.
equals() method in Java is used to check for equality between two maps.
You can index Dictionary, you didn't need 'get'.
Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);
An efficient way to test/get values is TryGetValue
(thanx to Earwicker):
if (otherExample.TryGetValue("key", out value))
{
otherExample["key"] = value + 1;
}
With this method you can fast and exception-less get values (if present).
Resources:
Dictionary-Keys
Try Get Value
Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).
class Test
{
Dictionary<int, string> entities;
public string GetEntity(int code)
{
// java's get method returns null when the key has no mapping
// so we'll do the same
string val;
if (entities.TryGetValue(code, out val))
return val;
else
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With