首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#中的Java Map等效项

C#中的Java Map等效项
EN

Stack Overflow用户
提问于 2009-03-26 23:30:15
回答 3查看 173.1K关注 0票数 157

我正在尝试使用我选择的键来保存集合中的项目列表。在Java中,我将简单地使用Map,如下所示:

代码语言:javascript
复制
class Test {
  Map<Integer,String> entities;

  public String getEntity(Integer code) {
    return this.entities.get(code);
  }
}

System.Collections.Generic.Hashset不使用散列,我也不能定义自定义类型键System.Collections.Hashtable不是泛型类

System.Collections.Generic.Dictionary没有get(Key)方法

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-03-26 23:33:07

你可以索引字典,你不需要'get‘。

代码语言:javascript
复制
Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

测试/获取值的一种有效方法是TryGetValue (thanx to Earwicker):

代码语言:javascript
复制
if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

使用此方法,您可以快速且无异常地获取值(如果存在)。

资源:

Dictionary-Keys

Try Get Value

票数 192
EN

Stack Overflow用户

发布于 2009-03-26 23:34:15

Dictionary<,>是等效的。虽然它没有Get(...)方法,它确实有一个名为Item的索引属性,您可以在C#中使用索引表示法直接访问该属性:

代码语言:javascript
复制
class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}

如果要使用自定义键类型,则应考虑实现IEquatable<>并覆盖Equals(object)和GetHashCode(),除非默认的(引用或结构)相等性足以确定键的相等性。您还应该使您的键类型不可变,以防止在将键插入到字典中后发生奇怪的事情(例如,因为突变导致其哈希码改变)。

票数 18
EN

Stack Overflow用户

发布于 2009-03-26 23:36:09

代码语言:javascript
复制
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;
    }
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/687942

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档