如何在初始化时定义地图内容?
我只是想知道是否可以在初始化时定义地图对象的内容。
例如,可以创建一个数组,如下所示:
new String[] {“apples”, “bananas”, “pears”}
所以,我想知道我们是否可以为地图做类似的事情。
I was just wondering if it is possible to define the contents of a Map Object on initialisation.
For example, an array can be created, as:
new String[] {“apples”, “bananas”, “pears”}
So, I was wondering if there is something similar we can do for maps.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的
Map
在创建后将是不可变的,并且您不介意添加依赖项,Guava 提供了一些不错的流畅语法:如果您感觉非常具有异国情调,Scala具有与您想要的语法完全相同的语法,并且可以与其他 Java 代码互操作:
请注意,Scala 编译器将推断
Map
泛型类型是从String
到Int,基于您放入的内容,尽管您也可以显式指定它。
但是,如果这只是一次性的,我会使用基于初始值设定项的语法。 Guava 库和 Scala 语言都有很多其他值得推荐的地方,但学习一个全新的库/语言可能有点过分了。
If your
Map
is going to be immutable after creation and you don't mind adding a dependency, Guava offers some nice fluent syntax:If you're feeling really exotic, Scala has syntax exactly like what you want and is interoperable with other Java code:
Note that the Scala compiler will infer the
Map
generic type is fromString
toInt
, based on what you put in it, though you can explicitly specify it as well.However, if this is just a one-off, I'd go with the initializer-based syntax. Both the Guava library and Scala language have a lot else to recommend them, but learning a whole new library/language might be overboard.
您可以使用初始化块:
You can use initializer blocks:
一些非常hacky的东西..可以改进,但这只是一个方向:
定义一个静态助手来将对象数组转换为这种类型的映射:
然后您可以使用它创建一个映射:
我个人会赞同 @Carl 的 Gauva 构建器建议:-)
Something very hacky..can be improved, but this is just a direction:
Define a static helper to convert an object array to a map of this type:
then you can create a map using this:
I would personally second Gauva builder suggestion from @Carl though :-)
您可以使用这种语法技巧:
不过,不太令人愉快。这将创建 HashMap 的匿名子类,并将其填充到实例初始值设定项中。
You can, sort of, using this syntax trick:
Not very pleasant, though. This creates an anonymous subclass of
HashMap
, and populates it in the instance initializer.