OOP:ArrayList al = new ArrayList()和List al = new ArrayList()之间的区别? [英] OOP: Difference between ArrayList al = new ArrayList() and List al = new ArrayList()?

查看:211
本文介绍了OOP:ArrayList al = new ArrayList()和List al = new ArrayList()之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

List与ArrayList

ArrayList al = new ArrayList() 

List al = new ArrayList() ?


推荐答案

两者都创建 ArrayList 的实例。

不同的是,在第二个例子中, al 允许访问 List 接口上实现的所有方法,而在第一个示例中, al 允许访问 ArrayList 类的所有(可访问)方法和字段。

The difference is that, in you second example, al allows access to all methods implemented on the List interface while, in the first example, al allows access to all (accessible) methods and fields of the ArrayList class.

thumb:使用第二个模式。如果你需要从 ArrayList 实现中获得一些额外的好处,那么你总是可以转换:

A practical rule of thumb: use the second pattern. If you need some extra goodies from the ArrayList implementation, then you can always cast:

 List list = new ArrayList();
 // do some adds/removes/... on the list
 ((ArrayList) list).trimToSize();

这篇关于OOP:ArrayList al = new ArrayList()和List al = new ArrayList()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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