我有一个构建 LinkedHashMap
的方法,这样我就可以保持顺序。这是我的方法:
public class MyClass {
public Map<String,MyObj> buildMap() {
Map<String,MyObj> myMap = new LinkedHashMap<>();
//perform logic and add objects to myMap
...
return myMap;
}
}
当我从另一个类调用我的 buildMap()
函数时,我会得到一个按顺序排列的 map 吗?喜欢:
MyClass myClass = new MyClass();
Map<String, MyObj> returnedMap = myClass.buildMap();
我的 returnedMap
仍然是 LinkedHashMap
吗?
或者我是否必须更改我的 buildMap
函数以始终返回 LinkedHashMap
?
最佳答案
返回什么类型或接口(interface)并不重要。但是,对象实例类型确实很重要。如果它是 LinkedHashMap
,那么它将保留实现,因此您的情况下的顺序。
This implementation spares its clients from the unspecified, generally chaotic ordering provided by
HashMap
(andHashtable
), without incurring the increased cost associated withTreeMap
. It can be used to produce a copy of a map that has the same order as the original, regardless of the original map's implementation:void foo(Map m) { Map copy = new LinkedHashMap(m); ... }
关于java - 如果我正在构建一个 linkedhashmap 并返回一个映射,我的调用函数是否会有一个 linkedhashmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44111138/