C#Java HashMap等价

时间:2009-08-13 16:35:58

标签: c# java hashmap

从Java世界进入C#,是否有HashMap等价物?如果不是你会推荐什么?

7 个答案:

答案 0 :(得分:421)

Dictionary可能是最接近的。 System.Collections.Generic.Dictionary实现了System.Collections.Generic.IDictionary接口(类似于Java的Map接口)。

您应该注意的一些值得注意的差异:

  • 添加/获取项目
    • Java的HashMap具有用于设置/获取项目的putget方法
      • myMap.put(key, value)
      • MyObject value = myMap.get(key)
    • C#的词典使用[]索引来设置/获取项目
      • myDictionary[key] = value
      • MyObject value = myDictionary[key]
  • null
    • Java的HashMap允许空键
    • 如果您尝试添加空密钥,.NET Dictionary会抛出ArgumentNullException
  • 添加重复的密钥
    • Java的HashMap将用新的值替换现有值。
    • 如果您使用Dictionary索引,.NET []将使用新值替换现有值。如果您使用Add方法,则会抛出ArgumentException
  • 尝试获取不存在的密钥
    • Java的HashMap将返回null。
    • .NET的Dictionary会抛出KeyNotFoundException。您可以使用TryGetValue方法而不是[]索引来避免这种情况:
      MyObject value = null; if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }

Dictionary有一个ContainsKey方法可以帮助解决前两个问题。

答案 1 :(得分:35)

来自C# equivalent to Java HashMap

我需要一个接受“null”键的词典,但似乎没有原生词,所以我写了自己的。实际上,它非常简单。我从Dictionary继承,添加了一个私有字段来保存“null”键的值,然后覆盖了索引器。它是这样的:

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;
            }
        }
    }
}

希望这有助于将来。

==========

我将其修改为此格式

public class NullableDictionnary : Dictionary<string, object>

答案 2 :(得分:9)

让我通过一个&#34; codaddict&#34;算法&#34;

的例子来帮助你理解它。 C#&#39;中的

&#39; 词典 Java&#39; Hashmap 并行宇宙。

有些实现是不同的。请参阅下面的示例以更好地理解。

声明Java HashMap:

Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();

声明C#字典:

Dictionary<int, int> Pairs = new Dictionary<int, int>();

从某个位置获取值:

pairs.get(input[i]); // in Java
Pairs[input[i]];     // in C#

在位置设置值:

pairs.put(k - input[i], input[i]); // in Java
Pairs[k - input[i]] = input[i];    // in C#

可以从Codaddict的算法下面观察整体示例。

使用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的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();
    }
}

答案 3 :(得分:5)

查看MSDN上Hashtable课程的文档。

  

表示根据键的哈希码组织的键 - 值对的集合。

另外,请记住,这不是线程安全的。

答案 4 :(得分:2)

使用字典 - 它使用哈希表,但是类型安全。

此外,您的

的Java代码
int a = map.get(key);
//continue with your logic

最好用C#编码:

int a;
if(dict.TryGetValue(key, out a)){
//continue with your logic
}

通过这种方式,您可以满足变量&#34; a&#34;在一个街区内,如果你以后需要它,它仍然可以在街区外进入。

答案 5 :(得分:0)

答案是

  

词典

看看我的函数,它的简单添加使用Dictionary

中最重要的成员函数

如果列表包含Duplicates items

,则此函数返回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 :(得分:0)

我只是想给我两分钱 这是根据@Powerlord的回答。

&#34; null&#34; 代替 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");
}