C#到Java - 字典? [英] C# to Java - Dictionaries?

查看:163
本文介绍了C#到Java - 字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中是否可以使用已在其中声明的项目创建一个Dictionary?就像下面的C#代码一样:

Is it possible in Java to make a Dictionary with the items already declared inside it? Just like the below C# code:

   Dictionary<string, int> d = new Dictionary<string, int>()
    {
        {"cat", 2},
        {"dog", 1},
        {"llama", 0},
        {"iguana", -1}
    };

我该怎么做以及我使用什么类型?我读过字典已经过时了。

How do I do this and what type do I use? I've read that Dictionary is obsolete.

推荐答案

这可以做你想做的事:

Map<String,Integer> map = new HashMap<String, Integer>(){{
    put("cat", 2);
    put("dog", 1);
    put("llama", 0);
    put("iguana", -1);
}};

此语句创建HashMap的匿名子类,其中与父类的唯一区别在于4在实例创建期间添加条目。它在Java世界中是一个相当普遍的习惯用法(尽管有些人认为它有争议,因为它创建了一个新的类定义)。

This statement creates an anonymous subclass of HashMap, where the only difference from the parent class is that the 4 entries are added during instance creation. It's a fairly common idiom in the Java world (although some find it controversial because it creates a new class definition).

由于这种争议,从Java 9开始,方便构建地图的新惯用语:静态族 Map.of方法

Because of this controversy, as of Java 9 there is a new idiom for conveniently constructing maps: the family of static Map.of methods.

使用Java 9或更高版本,您可以创建所需的地图,如下所示:

With Java 9 or higher you can create the map you need as follows:

Map<String, Integer> map = Map.of(
    "cat", 2,
    "dog", 1,
    "llama", 0,
    "iguana", -1
);

对于较大的地图,这个替代语法可能不太容易出错:

With larger maps, this alternative syntax may be less error-prone:

Map<String, Integer> map = Map.ofEntries(
    Map.entry("cat", 2),
    Map.entry("dog", 1),
    Map.entry("llama", 0),
    Map.entry("iguana", -1)
);

(如果静态导入Map.entry而不是显式引用,这个特别好。)

(This is especially nice if Map.entry is statically imported instead of being referenced explicitly).

除了仅使用Java 9+之外,这些新方法与前一种方法并不完全相同:

Besides only working with Java 9+, these new approaches are not quite equivalent to the previous one:


  • 他们不允许您指定使用的Map实现

  • 他们只创建不可变的地图

  • 他们不创建Map的匿名子类

但是,对于许多用例而言,这些差异无关紧要,这对于较新版本来说是一个很好的默认方法of Java。

However, these differences shouldn't matter for many use cases, making this a good default approach for newer versions of Java.

这篇关于C#到Java - 字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆