The Map.of, Map.ofEntries, and Map.copyOf static factory methods
provide a convenient way to create unmodifiable maps. The Map
instances created by these methods have the following characteristics:
...
The iteration order of mappings is unspecified and is subject to change.
Static factory methods on concrete collection classes (e.g., ArrayList, HashSet) have been removed from this proposal ...
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!
# 1 楼答案
如^{} (emphasis mine)的Java apidoc所述:
不幸的是,Java API中没有等效的便利方法来创建
LinkedHashMap
。如果想要一致的迭代顺序,那么需要手动创建一个LinkedHashMap
并填充它(如果需要,还需要使用Collections.unmodifiableMap
包装它)考虑创建自己的便利方法,该方法等效于^ {CD5>},但以一致的迭代顺序(或者找到一个已经提供的现有库)。p>
# 2 楼答案
实际上,没有像
LinkedHashMap::of
这样的工厂方法,而且Map
本身也没有顺序,所以我看到的唯一方法是,如果确实需要的话,构建一个LinkedHashMap
顺便说一句,从the JEP itself
这里的要点是
static
方法是继承的,但不可重写,因此,如果这样一个方法被添加到HashMap
中,它可能不会在LinkedHashMap
中被重写如果您可以使用
guava
,那么您可以使用ImmutableMap
,它被记录为:# 3 楼答案
你也可以使用vavr。io以以下方式进行: