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
基础教程推荐
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
