C# Java HashMap 等价物

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1273139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:31:25  来源:igfitidea点击:

C# Java HashMap equivalent

c#javahashmap

提问by John

Coming from a Java world into a C# one is there a HashMap equivalent? If not what would you recommend?

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

采纳答案by Powerlord

Dictionaryis probably the closest. System.Collections.Generic.Dictionaryimplements the System.Collections.Generic.IDictionaryinterface (which is similar to Java's Mapinterface).

Dictionary可能是最接近的。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 putand getmethods 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 an ArgumentNullExceptionif 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 the Addmethod, it will instead throw an ArgumentException.
  • Attempting to get a non-existent key
    • Java's HashMapwill return null.
    • .NET's Dictionarywill throw a KeyNotFoundException. You can use the TryGetValuemethod instead of the []indexing to avoid this:
      MyObject value = null; if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }
  • 添加/获取项目
    • Java 的 HashMap 具有用于设置/获取项目的putget方法
      • myMap.put(key, value)
      • MyObject value = myMap.get(key)
    • C# 的字典使用[]索引来设置/获取项目
      • myDictionary[key] = value
      • MyObject value = myDictionary[key]
  • null钥匙
    • JavaHashMap允许空键
    • 如果您尝试添加空键,.NET 会Dictionary抛出一个ArgumentNullException
  • 添加重复键
    • JavaHashMap将用新值替换现有值。
    • Dictionary如果您使用[]索引,.NET将用新值替换现有值。如果您使用该Add方法,它将改为抛出ArgumentException.
  • 试图获取不存在的密钥
    • JavaHashMap将返回 null。
    • .NETDictionary会抛出一个KeyNotFoundException. 您可以使用该TryGetValue方法而不是[]索引来避免这种情况:
      MyObject value = null; if (!myDictionary.TryGetValue(key, out value)) { /* key doesn't exist */ }

Dictionary's has a ContainsKeymethod that can help deal with the previous two problems.

Dictionary的有一个ContainsKey方法可以帮助处理前两个问题。

回答by Ray

Check out the documentation on MSDN for the Hashtableclass.

查看 MSDN 上关于Hashtable类的文档。

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.

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

回答by KeithC

From C# equivalent to Java HashMap

C# 相当于 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>

回答by Ajay Yadiki

Let me help you understand it with an example of "codaddict's algorithm"

让我用“codaccident's algorithm”的例子来帮助你理解它

'Dictionaryin C#' is 'Hashmapin Java' in parallel universe.

' C#中的字典'是平行宇宙中的' 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.

可以从下面的 Codacci 算法中观察到一个整体示例。

codaddict's algorithm in Java:

Java 中的 codacci 算法:

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#

C# 中的 Codacci 算法

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

回答by Basheer AL-MOMANI

the answer is

答案是

Dictionary

字典

take look at my function, its simple add uses most important member functions inside Dictionary

看看我的函数,它的简单 add 使用了 Dictionary 中最重要的成员函数

this function return false if the list contain 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
    }

回答by ossobuko

I just wanted to give my two cents.
This is according to @Powerlord 's answer.

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

Puts "null"instead of nullstrings.

放置“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");
}

回答by Shree Harsha

Use Dictionary - it uses hashtable but is typesafe.

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

Also, your Java code for

此外,您的 Java 代码

int a = map.get(key);
//continue with your logic

will be best coded in C# this way:

最好用 C# 这种方式编码:

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.

这样,您可以在块内确定变量“a”的需要范围,并且如果您以后需要它,它仍然可以在块外访问。