列出与ArrayList的参考类型? [英] List versus ArrayList as reference type?
问题描述
好了,所以我知道,设置
,列表
和地图
的接口,但是是什么让code的第一行的任何比第二行更好呢?
列表myArr,该=新的ArrayList();
ArrayList的myArr,该=新的ArrayList();
如果您使用第一种形式,你说你曾经打算使用所有的是列表$ C的功能$ C>接口 - 不出意外,尤其是没有额外的由它执行任何添加。这意味着您可以轻松地更改使用(例如刚刚替补
的LinkedList
为的ArrayList
在实例)的实施,而不必担心它打破了code的休息,因为你可能已经使用特定于的ArrayList
的东西。
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();
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
.
这篇关于列出与ArrayList的参考类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!