List 与 ArrayList 作为引用类型? [英] List versus ArrayList as reference type?
问题描述
好的,我知道 Set
、List
和 Map
是接口,但是是什么让第一行代码比第二行更好?
Ok so I know that Set
, List
and Map
are interfaces but what makes the first line of code any better than the second line?
List myArr = new ArrayList();
ArrayList myArr = new ArrayList();
推荐答案
如果你使用第一种形式,你就是说你将要使用的只是 List
接口的功能 - 没什么否则,尤其是它的任何实现都没有添加任何额外的东西.这意味着您可以轻松更改所使用的实现(例如,只需在实例化中将 LinkedList
替换为 ArrayList
),而不必担心它会破坏其余代码,因为您可能有使用了特定于 ArrayList
的东西.
If you use the first form, you are saying all you are ever going to use is the functionality of the List
interface - nothing else, especially nothing extra added by any implementation of it. This means you can easily change the implementation used (e.g. just substitute LinkedList
for ArrayList
in the instantiation), and not worry about it breaking the rest of the code because you might have used something specific to ArrayList
.
这篇关于List 与 ArrayList 作为引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!