在Java中键入List vs type ArrayList [英] Type List vs type ArrayList in Java

查看:150
本文介绍了在Java中键入List vs type ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(1) List<?> myList = new ArrayList<?>();

(2) ArrayList<?> myList = new ArrayList<?>();

我理解用(1), List 界面的实现可以被交换。似乎(1)通常在应用程序中使用而不管需要(我自己总是使用它)。

I understand that with (1), implementations of the List interface can be swapped. It seems that (1) is typically used in an application regardless of need (myself I always use this).

我想知道是否有人使用(2)?

I am wondering if anyone uses (2)?

此外,多久(我可以得到一个例子)情况实际上需要使用(1)over(2)(即where(2)不会足够..除了 编码接口 最佳做法 等。)

Also, how often (and can I please get an example) does the situation actually require using (1) over (2) (i.e. where (2) wouldn't suffice..aside coding to interfaces and best practices etc.)

推荐答案

几乎总是第一个比第二个更受欢迎。第一个优点是 List 的实现可以改变(到 LinkedList 例如),不影响其余代码。使用 ArrayList 这将是一项艰巨的任务,不仅因为您需要将 ArrayList 更改为 LinkedList 无处不在,还因为您可能使用过 ArrayList 特定方法。

Almost always the first one is preferred over the second one. The first has the advantage that the implementation of the List can change (to a LinkedList for example), without affecting the rest of the code. This will be a difficult task to do with an ArrayList, not only because you will need to change ArrayList to LinkedList everywhere, but also because you may have used ArrayList specific methods.

您可以阅读列表实现这里。您可以从 ArrayList 开始,但不久之后发现另一个实现更合适。

You can read about List implementations here. You may start with an ArrayList, but soon afterwards discover that another implementation is more appropriate.

这篇关于在Java中键入List vs type ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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