【问题标题】:Why usually Map<X, X> = new HashMap<X, X>() instead of HashMap<X, X> = new HashMap<X, X>()? [duplicate]为什么通常 Map<X, X> = new HashMap<X, X>() 而不是 HashMap<X, X> = new HashMap<X, X>()? [复制]
【发布时间】:2011-11-25 09:18:37
【问题描述】:

可能重复:
Isn't it easier to work with foo when it is represented by the class ArrayList rather than the interface List?
Why are most of the examples using ArrayList

为什么我们大多这样做

Map<Integer, String> map = new HashMap<Integer, String>();

而不是

HashMap<Integer, String> map = new HashMap<Integer, String>();

& 在实例化 ArrayList(s) 时类似。

【问题讨论】:

    标签: java collections


    【解决方案1】:

    键入更少,Map 是该类的接口(与 List 相同),因此传递 Map 比传递 HashMap 更容易,因为功能相同,唯一的区别是实现。这通常是这样做的(在某些情况下),当让我们说由于某种原因您决定 HashMap 不是您想要的并且您想使用 TreeMap 而不是在您的所有代码中都有 HashMap 参数并且更改这些参数可能会很痛苦。如果您改为传递 Map,则无需更改任何内容,并且您的代码可以更加灵活。

    【讨论】:

    • 不仅仅是从一种类型转换为另一种类型(HashMap 到 TreeMap),还支持多态性。你应该依赖契约(接口)而不是对象的内部实现。
    • @ewernli 我知道我想举个例子,所以我想我错过了这一点。
    猜你喜欢
    • 2014-11-12
    • 2021-10-07
    • 2013-08-29
    • 2013-07-10
    • 1970-01-01
    • 2019-03-27
    • 2023-03-04
    • 2015-10-26
    • 2020-03-18
    相关资源
    最近更新 更多