如何在Map.of工厂中保留插入顺序? [英] How to preserve order of insertion in Map.of factory?

查看:139
本文介绍了如何在Map.of工厂中保留插入顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 9提供了 Map.of()功能,可以轻松创建具有固定值的地图。

Java 9 offers Map.of() feature to easily create a map with fixed values.

问题:我想创建一个保留插入顺序的地图,如 LinkedHashMap 。这个工厂有可能吗?至少 map.of()不保存订单......

Problem: I want to create a map that preserves order of insertion like LinkedHashMap. Is that possible with that factory? At least map.of() does not preserv the order...

推荐答案

确实没有类似 LinkedHashMap :: of 的工厂方法,并且 Map 没有订单本身,所以我看到的唯一方法是建立一个 LinkedHashMap 如果你真的需要一个。

There isn't a factory method like LinkedHashMap::of indeed, and a Map does not have an order per-se, so the only way I see it is to build a LinkedHashMap if you really needed one.

来自 JEP本身的信息:


具体集合类(例如,ArrayList,HashSet)上的静态工厂方法已从此提案中删除...

Static factory methods on concrete collection classes (e.g., ArrayList, HashSet) have been removed from this proposal ...

还有另一个问题,即类的静态方法是由子类继承的。假设要添加静态工厂方法HashMap.of()。由于LinkedHashMap是HashMap的子类,因此应用程序代码可以调用LinkedHashMap.of()。这最终会调用HashMap.of(),而不是人们所期望的!

There is another wrinkle, which is that static methods on classes are inherited by subclasses. Suppose a static factory method HashMap.of() were to be added. Since LinkedHashMap is a subclass of HashMap, it would be possible for application code to call LinkedHashMap.of(). This would end up calling HashMap.of(), not at all what one would expect!

这里指的是 static 方法是继承的,但不能覆盖,因此如果这样的方法已添加到 HashMap ,则可能未在 LinkedHashMap 中覆盖。

Point here is that static methods are inherited, but not overridable, thus if such a method would have been added to HashMap it could have not been overridden in LinkedHashMap.

如果你可以使用 guava ,你可以使用 ImmutableMap

If you can use guava, you could use ImmutableMap that is documented as:


基于哈希的不可变Map,具有可靠的用户指定迭代顺序......

An immutable, hash-based Map with reliable user-specified iteration order...

这篇关于如何在Map.of工厂中保留插入顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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