如果我正在构建 linkedhashmap 和 return 地图,我的调用函数是否会有 linkedhashmap

If I'm building a linkedhashmap and return a map, would my calling function have a linkedhashmap

我有一个构建 LinkedHashMap 的方法,这样我就可以保持秩序。这是我的方法:

public class MyClass {

    public Map<String,MyObj> buildMap() {
        Map<String,MyObj> myMap = new LinkedHashMap<>();
        //perform logic and add objects to myMap
        ...
        return myMap;
    }
}

当我从另一个 class 调用我的 buildMap() 函数时,我会得到一个按顺序排列的地图吗?喜欢:

MyClass myClass = new MyClass();
Map<String, MyObj> returnedMap = myClass.buildMap();

我的 returnedMap 还会是 LinkedHashMap 吗?

或者我是否必须将 buildMap 函数更改为始终 return a LinkedHashMap

返回什么类型或接口并不重要。但是,对象实例类型确实很重要。如果它是 LinkedHashMap 那么它将保留实现,因此您的情况下的顺序。

This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap. 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);
     ...
 }

另一个答案是正确的 - 您在源代码中使用什么 return 类型 来表达您的想法并不重要。

在运行时,唯一与对象的性质有关的是它的具体、具体 class。

但要考虑的一方面是:如果 "keeping insertion order" 是您提供给用户的 API 的 核心 元素,您 可能将您的方法签名更改为:

public LinkedHashMap<String,MyObj> buildMap() {

简单地让此方法的所有未来用户清楚该方法正在做什么。

你看,LinkedHashMap 和 HashMap 具有稍微不同的performance特征。根据您的上下文,可能对于未来的调用者了解该方法实际上return这个特殊的 Map 实现很重要。

但在大多数情况下,这种差异并不重要,然后是"good practice"到return更抽象的接口类型而不是具体实现class。请参阅 here 进一步阅读为什么通常更喜欢 interface 类型。