List 与 ArrayList 作为引用类型? [英] List versus ArrayList as reference type?

查看:31
本文介绍了List 与 ArrayList 作为引用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我知道 SetListMap 是接口,但是是什么让第一行代码比第二行更好?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆