C# 到 Java - 字典?
在Java中是否可以制作一个包含已在其中声明的项目的字典?就像下面的 C# 代码一样:
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"cat", 2},
{"dog", 1},
{"llama", 0},
{"iguana", -1}
};
我该如何执行此操作以及我使用什么类型?我读到字典已经过时了。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这将执行您想要的操作:
此语句创建 HashMap 的匿名子类,其中与父类的唯一区别是在实例创建期间添加了 4 个条目。这是 Java 世界中相当常见的习惯用法(尽管有些人认为它有争议,因为它创建了一个新的类定义)。
由于这个争议,从 Java 9 开始,出现了一种可以方便地构建映射的新习惯用法:静态 Map.of 方法。
使用 Java 9 或更高版本,您可以按如下方式创建所需的地图:
对于较大的地图,此 替代语法可能不太容易出错:(
如果 Map.entry 是静态导入而不是被引用,这尤其好明确)。
除了仅适用于 Java 9+ 之外,这些新方法与前一种方法并不完全相同:
但是,这些差异对于许多用例来说并不重要,这使得这成为新版本 Java 的良好默认方法。
This will do what you want:
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).
Because of this controversy, as of Java 9 there is a new idiom for conveniently constructing maps: the family of static Map.of methods.
With Java 9 or higher you can create the map you need as follows:
With larger maps, this alternative syntax may be less error-prone:
(This is especially nice if Map.entry is statically imported instead of being referenced explicitly).
Besides only working with Java 9+, these new approaches are not quite equivalent to the previous one:
However, these differences shouldn't matter for many use cases, making this a good default approach for newer versions of Java.
硬着头皮打出地图名称!
您也可以执行类似的操作,这可能会节省一些输入长列表的操作:
Bite the bullet and type out the map name!
You could also do something like this, which might save some typing with a long list:
如果您使用 Guava 库,则可以使用其
ImmutableMap
类,或者单独使用(示例 1 和 2),或作为 HashMap 的初始化器(示例 3 和 4):If you use the Guava library, you can use its
ImmutableMap
class, either by itself (examples 1 and 2), or as an initializer for a HashMap (examples 3 and 4):Java7 几乎引入了允许这样的语法的“集合文字”。他们可能会尝试将其推入 Java8。我不知道这些人出了什么问题。
这可以通过某种包装 API 轻松实现,
还不错。我更喜欢这样的东西,
这种东西必须由不同的人实现,不幸的是标准API不包含这样的东西。
Java7 almost introduced "collection literals" that would allow syntax like that. They'll probably try to shove it in Java8. I have no idea what is wrong with these people.
This can be easily achieved by some kind of wrapper API
Not too bad. I would prefer something like
This kind of thing must have been implemented by various people, unfortunately the standard API doesn't inculde such things.