本文翻译自:C# Java HashMap equivalent
Coming from a Java world into a C# one is there a HashMap equivalent? 从Java世界变成C#,有一个HashMap等价物吗? If not what would you recommend? 如果不是你会推荐什么?
#1楼
参考:https://stackoom.com/question/5LCV/C-Java-HashMap等价
#2楼
Dictionary
is probably the closest. Dictionary
可能是最接近的。 System.Collections.Generic.Dictionary
implements the System.Collections.Generic.IDictionary
interface (which is similar to Java's Map
interface). System.Collections.Generic.Dictionary
实现System.Collections.Generic.IDictionary
接口(类似于Java的Map
接口)。
Some notable differences that you should be aware of: 您应该注意的一些值得注意的差异:
- Adding/Getting items 添加/获取项目
- Java's HashMap has the
put
andget
methods for setting/getting items Java的HashMap具有用于设置/获取项目的put
和get
方法-
myMap.put(key, value)
-
MyObject value = myMap.get(key)
-
- C#'s Dictionary uses
[]
indexing for setting/getting items C#的Dictionary使用[]
索引来设置/获取项目-
myDictionary[key] = value
-
MyObject value = myDictionary[key]
-
- Java's HashMap has the
-
null
keysnull
键- Java's
HashMap
allows null keys Java的HashMap
允许使用null键 - .NET's
Dictionary
throws anArgumentNullException
if you try to add a null key 如果您尝试添加null键,.NET的Dictionary
会抛出ArgumentNullException
- Java's
- Adding a duplicate key 添加重复的密钥
- Java's
HashMap
will replace the existing value with the new one. Java的HashMap
将用新的值替换现有的值。 - .NET's
Dictionary
will replace the existing value with the new one if you use[]
indexing. 如果使用[]
索引,.NET的Dictionary
将用新的值替换现有值。 If you use theAdd
method, it will instead throw anArgumentException
. 如果使用Add
方法,它将抛出ArgumentException
。
- Java's
- Attempting to get a non-existent key 试图获得一个不存在的密钥
- Java's
HashMap
will return null. Java的HashMap
将返回null。 - .NET's
Dictionary
will throw aKeyNotFoundException
. .NET的Dictionary
会抛出一个KeyNotFoundException
。 You can use theTryGetValue
method instead of the[]
indexing to avoid this: 您可以使用TryGetValue
方法而不是[]
索引来避免这种情况: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. Dictionary
的有一个ContainsKey
方法,可以帮助处理前两个问题。
#3楼
Check out the documentation on MSDN for the Hashtable class. 查看有关Hashtable类的MSDN文档。
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. 另外,请记住,这不是线程安全的。
#4楼
Let me help you understand it with an example of "codaddict's algorithm" 让我通过“codaddict算法”的例子来帮助你理解它
' Dictionary in C#' is ' Hashmap in Java' in parallel universe. “C#中的字典 ”是并行Universe中的“Java中的Hashmap ”。
Some implementations are different. 一些实现是不同的。 See the example below to understand better. 请参阅下面的示例以更好地了解。
Declaring Java HashMap: 声明Java HashMap:
Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();
Declaring C# Dictionary: 声明C#字典:
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的算法下面可以观察到一个总体例子。
codaddict's algorithm in Java: Java中的codaddict算法:
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# Codaddict在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();
}
}
#5楼
the answer is 答案是
Dictionary 字典
take look at my function, its simple add uses most important member functions inside Dictionary 看看我的函数,它的简单添加使用了Dictionary中最重要的成员函数
this function return false if the list contain Duplicates items 如果列表包含Duplicates项,则此函数返回false
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
}
#6楼
I just wanted to give my two cents. 我只是想给我两分钱。
This is according to @Powerlord 's answer. 这是根据@Powerlord的回答。
Puts "null" instead of null strings. 设置“null”而不是空字符串。
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");
}