java 我需要一个保留插入顺序的不可变键值结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14982820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I need an immutable key-value structure that retains insertion order
提问by Oleksandr Karaberov
I want to find something like ImmutableLinkedHashMap<>
in Guava library.
I need to use an immutable key-value data structure with an insertion order.
So, what should I use?
我想ImmutableLinkedHashMap<>
在番石榴图书馆中找到类似的东西。我需要使用具有插入顺序的不可变键值数据结构。那么,我应该使用什么?
回答by mdm
I am not sure I am understanding exactly what you are after, but if it is a really immutable Map
, you mght want to look at ImmutableMap
我不确定我是否完全理解你所追求的,但如果它真的是不可变的Map
,你可能想看看ImmutableMap
As mentioned in the doc:
如文档中所述:
An immutable, hash-based
Map
with reliable user-specified iteration order. Does not permit null keys or values.Unlike
Collections.unmodifiableMap(java.util.Map<? extends K, ? extends V>)
, which is a view of a separate map which can still change, an instance ofImmutableMap
contains its own data and will never change.ImmutableMap
is convenient forpublic static final
maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller
一个不可变的,基于哈希的,
Map
具有可靠的用户指定的迭代顺序。不允许空键或值。与
Collections.unmodifiableMap(java.util.Map<? extends K, ? extends V>)
是一个仍然可以改变的单独地图的视图不同, 的实例ImmutableMap
包含它自己的数据并且永远不会改变。ImmutableMap
对于public static final
地图(“常量地图”)很方便,还可以让您轻松制作由调用者提供给您的班级的地图的“防御副本”
E.g, you could use it in a similar fashion:
例如,您可以以类似的方式使用它:
Map<Integer, String> m = ImmutableMap.of(5,"Five",6,"Six",7,"Seven");
Hope this is what you were after.
希望这就是你所追求的。
回答by dogbane
First create a LinkedHashMap
and then use ImmutableMap.copyOf(linkedHashMap)
to create an immutable copy which will have the same ordering as the original map.
首先创建一个LinkedHashMap
,然后用于ImmutableMap.copyOf(linkedHashMap)
创建一个与原始地图具有相同顺序的不可变副本。