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 Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
