问题
Coming from a Java world into a C# one is there a HashMap equivalent? If not what would you recommend?
回答1:
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 itemsmyMap.put(key, value)MyObject value = myMap.get(key)
- C#'s Dictionary uses
[]indexing for setting/getting itemsmyDictionary[key] = valueMyObject value = myDictionary[key]
- Java's HashMap has the
nullkeys- Java's
HashMapallows null keys - .NET's
Dictionarythrows anArgumentNullExceptionif you try to add a null key
- Java's
- 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.
- Java's
- Attempting to get a non-existent key
- Java's
HashMapwill return null. - .NET's
Dictionarywill throw aKeyNotFoundException. You can use the TryGetValue 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.
回答2:
From C# equivalent to Java HashMap
I needed a Dictionary which accepted a "null" key, but there seems to be no native one, so I have written my own. It's very simple, actually. I inherited from Dictionary, added a private field to hold the value for the "null" key, then overwritten the indexer. It goes like this :
public class NullableDictionnary : Dictionary<string, string>
{
string null_value;
public StringDictionary this[string key]
{
get
{
if (key == null)
{
return null_value;
}
return base[key];
}
set
{
if (key == null)
{
null_value = value;
}
else
{
base[key] = value;
}
}
}
}
Hope this helps someone in the future.
==========
I modified it to this format
public class NullableDictionnary : Dictionary<string, object>
回答3:
Let me help you understand it with an example of "codaddict's algorithm"
'Dictionary in C#' is 'Hashmap in Java' in parallel universe.
Some implementations are different. See the example below to understand better.
Declaring Java HashMap:
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
Declaring C# Dictionary:
Dictionary<int, int> Pairs = new Dictionary<int, int>();
Getting a value from a location:
pairs.get(input[i]); // in Java
Pairs[input[i]]; // in C#
Setting a value at location:
pairs.put(k - input[i], input[i]); // in Java
Pairs[k - input[i]] = input[i]; // in C#
An Overall Example can be observed from below Codaddict's algorithm.
codaddict's algorithm in Java:
import java.util.HashMap;
public class ArrayPairSum {
public static void printSumPairs(int[] input, int k)
{
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
for (int i = 0; i < input.length; i++)
{
if (pairs.containsKey(input[i]))
System.out.println(input[i] + ", " + pairs.get(input[i]));
else
pairs.put(k - input[i], input[i]);
}
}
public static void main(String[] args)
{
int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
printSumPairs(a, 10);
}
}
Codaddict's algorithm in C#
using System;
using System.Collections.Generic;
class Program
{
static void checkPairs(int[] input, int k)
{
Dictionary<int, int> Pairs = new Dictionary<int, int>();
for (int i = 0; i < input.Length; i++)
{
if (Pairs.ContainsKey(input[i]))
{
Console.WriteLine(input[i] + ", " + Pairs[input[i]]);
}
else
{
Pairs[k - input[i]] = input[i];
}
}
}
static void Main(string[] args)
{
int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
//method : codaddict's algorithm : O(n)
checkPairs(a, 10);
Console.Read();
}
}
回答4:
Check out the documentation on MSDN for the Hashtable class.
Represents a collection of key-and-value pairs that are organized based on the hash code of the key.
Also, keep in mind that this is not thread-safe.
回答5:
Use Dictionary - it uses hashtable but is typesafe.
Also, your Java code for
int a = map.get(key);
//continue with your logic
will be best coded in C# this way:
int a;
if(dict.TryGetValue(key, out a)){
//continue with your logic
}
This way, you can scope the need of variable "a" inside a block and it is still accessible outside the block if you need it later.
回答6:
the answer is
Dictionary
take look at my function, its simple add uses most important member functions inside Dictionary
this function return false if the list contain Duplicates items
public static bool HasDuplicates<T>(IList<T> items)
{
Dictionary<T, bool> mp = new Dictionary<T, bool>();
for (int i = 0; i < items.Count; i++)
{
if (mp.ContainsKey(items[i]))
{
return true; // has duplicates
}
mp.Add(items[i], true);
}
return false; // no duplicates
}
回答7:
I just wanted to give my two cents.
This is according to @Powerlord 's answer.
Puts "null" instead of null strings.
private static Dictionary<string, string> map = new Dictionary<string, string>();
public static void put(string key, string value)
{
if (value == null) value = "null";
map[key] = value;
}
public static string get(string key, string defaultValue)
{
try
{
return map[key];
}
catch (KeyNotFoundException e)
{
return defaultValue;
}
}
public static string get(string key)
{
return get(key, "null");
}
来源:https://stackoverflow.com/questions/1273139/c-sharp-java-hashmap-equivalent