Java 中的类型列表与类型 ArrayList [英] Type List vs type ArrayList in Java
问题描述
(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)而不是(2)(即其中(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
优于 ArrayList
因为,例如,List
> 可以翻译成LinkedList
不影响代码库的其余部分.
Almost always List
is preferred over ArrayList
because, for instance, List
can be translated into a LinkedList
without affecting the rest of the codebase.
如果使用ArrayList
而不是List
,则很难将ArrayList
实现更改为LinkedList
实现因为在代码库中使用了 ArrayList
特定方法,这些方法也需要重构.
If one used ArrayList
instead of List
, it's hard to change the ArrayList
implementation into a LinkedList
one because ArrayList
specific methods have been used in the codebase that would also require restructuring.
您可以阅读List
实现这里.
您可以从 ArrayList
开始,但很快就会发现另一个实现是更合适的选择.
You may start with an ArrayList
, but soon after discover that another implementation is the more appropriate choice.
这篇关于Java 中的类型列表与类型 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!