gpt4 book ai didi

java - 为什么通常 Map = new HashMap() 而不是 HashMap = new HashMap()?

转载 作者:行者123 更新时间:2023-12-01 14:06:23 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:




10年前关闭。




Possible Duplicate:
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) 时类似。

最佳答案

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

关于java - 为什么通常 Map<X, X> = new HashMap<X, X>() 而不是 HashMap<X, X> = new HashMap<X, X>()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8266904/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com