Java 中的类型 List 与类型 ArrayList

Type List vs type ArrayList in Java(Java 中的类型 List 与类型 ArrayList)

本文介绍了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

基础教程推荐