Type List vs type ArrayList in Java(Java 中的类型 List 与类型 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) 而不是 (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
实现的信息 这里.
You can read about the List
implementations here.
您可能从 ArrayList
开始,但很快就会发现另一个实现是更合适的选择.
You may start with an ArrayList
, but soon after discover that another implementation is the more appropriate choice.
这篇关于Java 中的类型 List 与类型 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 中的类型 List 与类型 ArrayList


- 获取数字的最后一位 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01