何时在 Java 中对数组使用列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1589813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:31:57  来源:igfitidea点击:

When to use a List over an Array in Java?

javaarrayslistdata-structures

提问by John Moffitt

In Java, when would it be preferential to use a List rather than an Array?

在 Java 中,什么时候优先使用 List 而不是 Array?

采纳答案by Tom Neyland

I see the question as being the opposite-

我认为这个问题是相反的-

When should you use an Array over a List?

什么时候应该在列表上使用数组?

Only you have a specific reason to do so (eg: Project Constraints, Memory Concerns (not really a good reason), etc.)

只有你有一个特定的理由这样做(例如:项目约束、内存问题(不是一个很好的理由)等)

Lists are much easier to use (imo), and have much more functionality.

列表更易于使用 (imo),并且具有更多功能。

Note: You should also consider whether or not something like a Set, or another datastructure is a better fit than a List for what you are trying to do.

注意:您还应该考虑 Set 或其他数据结构之类的东西是否比 List 更适合您要执行的操作。

Each datastructure, and implmentation, has different pros/cons. Pick the ones that excel at the things that you need to do.

每个数据结构和实现都有不同的优缺点。选择那些在你需要做的事情上表现出色的人。

If you need get() to be O(1) for any item? Likely use an ArrayList, Need O(1) insert()? Possibly a Linked List. Need O(1) contains()? Possibly a Hashset.

如果您需要 get() 为任何项目的 O(1) ?可能使用 ArrayList,需要 O(1) insert() 吗?可能是链表。需要 O(1) contains() 吗?可能是一个哈希集。

TLDR: Each data structure is good at some things, and bad at others. Look at your objectives and choose the data structure that best fits the given problem.

TLDR:每种数据结构都擅长某些方面,而在其他方面却很差。查看您的目标并选择最适合给定问题的数据结构。

Edit:

编辑:

One thing not noted is that you're better off declaring the variable as its interface (i.e. List or Queue) rather than its implementing class. This way, you can change the implementation at some later date without changing anything else in the code.

As an example:

没有注意到的一件事是,最好将变量声明为其接口(即列表或队列)而不是其实现类。这样,您可以在以后更改实现,而无需更改代码中的任何其他内容。

举个例子:

List<String> myList = new ArrayList<String>(); 

vs

对比

List<String> myList = new LinkedList<String>(); 

Note that myList is a List in both examples. --R. Bemrose

请注意,在两个示例中 myList 都是一个 List。- R. Bemrose

回答by John Moffitt

If you want the array of items to expand (i.e. if you don't know what the size of the list will be beforehand), a List will be beneficial. However, if you want performance, you would generally use an array.

如果您希望项目数组扩展(即,如果您事先不知道列表的大小),List 将是有益的。但是,如果您想要性能,通常会使用数组。

回答by Chris Kessel

Pretty much always prefer a list. Lists have much more functionality, particularly iterator support. You can convert a list to an array at any time with the toArray() method.

几乎总是喜欢一个列表。列表有更多的功能,特别是迭代器支持。您可以随时使用 toArray() 方法将列表转换为数组。

回答by Jonathan Feinberg

It depends on what kind of List.

这取决于什么样的List。

It's better to use a LinkedList if you know you'll be inserting many elements in positions other than the end. LinkedList is not suitable for random access (getting the i'th element).

如果您知道将在末尾以外的位置插入许多元素,则最好使用 LinkedList。LinkedList 不适合随机访问(获取第 i 个元素)。

It's better to use an ArrayList if you don't know, in advance, how many elements there are going to be. The ArrayList correctly amortizes the cost of growing the backing array as you add more elements to it, and is suitable for random access once the elements are in place. An ArrayList can be efficiently sorted.

如果您事先不知道将有多少元素,最好使用 ArrayList。ArrayList 正确地分摊了增加后备数组的成本,因为您向它添加了更多元素,并且一旦元素就位就适合随机访问。ArrayList 可以有效地排序。

回答by p3t0r

In many cases the type of collection used is an implementation detail which shouldn't be exposed to the outside world. The more generic your returntype is the more flexibility you have changing the implementation afterwards.

在许多情况下,所使用的集合类型是一个不应向外界公开的实现细节。您的返回类型越通用,您之后更改实现的灵活性就越大。

Arrays (primitive type, ie. new int[10]) are not generic, you won't be able to change you implementation without an internal conversion or altering the client code. You might want to consider Iterable as a returntype.

数组(原始类型,即 new int[10])不是通用的,如果不进行内部转换或更改客户端代码,您将无法更改您的实现。您可能希望将 Iterable 视为返回类型。

回答by Dean J

If you know how many things you'll be holding, you'll want an array. My screen is 1024x768, and a buffer of pixels for that isn't going to change in size everduring runtime.

如果你知道你将持有多少东西,你会想要一个数组。我的屏幕为1024x768,并为像素的缓冲区不会在大小上改变以往运行时。

If you know you'll need to access specific indexes (go get item #763!), use an array or array-backed list.

如果你知道你需要访问特定的索引(去获取项目 #763!),使用数组或数组支持的列表。

If you need to add or remove items from the group regularly, use a linked list.

如果您需要定期从组中添加或删除项目,请使用链表。

In general, dealing with hardware, arrays, dealing with users, lists.

一般来说,处理硬件,数组,处理用户,列表。

回答by Tom Hawtin - tackline

Rules of thumb:

经验法则:

  • Use a Listfor reference types.
  • Use arrays for primitives.
  • If you have to deal with an API that is using arrays, it might be useful to use arrays. OTOH, it may be useful to enforce defensive copying with the type system by using Lists.
  • If you are doing a lot of Listtype operations on the sequence and it is not in a performance/memory critical section, then use List.
  • Low-level optimisations may use arrays. Expect nastiness with low-level optimisations.
  • 使用 aList作为引用类型。
  • 将数组用于基元。
  • 如果您必须处理使用数组的 API,则使用数组可能很有用。OTOH,通过使用Lists来强制使用类型系统进行防御性复制可能很有用。
  • 如果您正在List对序列进行大量类型操作并且它不在性能/内存临界区,那么使用List.
  • 低级优化可能使用数组。期待低级优化的肮脏。

回答by Surya

Always prefer lists.

总是喜欢列表。

Arrays when

数组时

  1. Varargs for a method ( I guess you are forced to use Arrays here ).
  2. When you want your collections to be covariant ( arrays of reference types are covariant ).
  3. Performance critical code.
  1. 方法的可变参数(我猜你在这里被迫使用数组)。
  2. 当您希望您的集合协变时(引用类型的数组是协变的)。
  3. 性能关键代码。

回答by vdr

Most people have answered it already.

大多数人已经回答了。

There are almost no good reason to use an array instead of List. The main exception being the primitive array (like int[]). You cannot create a primitive list (must have List<Integer>).

几乎没有充分的理由使用数组而不是 List。主要的例外是原始数组(如int[])。您不能创建原始列表(必须有List<Integer>)。

The most important difference is that when using List you can decide what implementation will be used. The most obvious is to chose LinkedList or ArrayList.

最重要的区别是,在使用 List 时,您可以决定将使用什么实现。最明显的就是选择LinkedList或者ArrayList。

I would like to point out in this answer that choosing the implementation gives you very fine grained control over the data that is simply not available to array:

我想在这个答案中指出,选择实现可以让您对数组根本不可用的数据进行非常细粒度的控制:

  1. You can prevent client from modifying your list by wrapping your list in a Collection.unmodifiableList
  2. You can synchronize a list for multithreading using Collection.synchronizedList
  3. You can create a fixed length queue with implementation of LinkedBlockingQueue
  4. ... etc
  1. 您可以通过将您的列表包装在一个 Collection.unmodifiableList
  2. 您可以使用同步多线程列表 Collection.synchronizedList
  3. 您可以通过实现来创建一个固定长度的队列 LinkedBlockingQueue
  4. ... 等等

In any case, even if you don't want (now) any extra feature of the list. Just use an ArrayList and size it with the size of the array you would have created. It will use an Array in the back-end and the performance difference with a real array will be negligible. (except for primitive arrays)

无论如何,即使您(现在)不想要列表的任何额外功能。只需使用一个 ArrayList 并根据您将创建的数组的大小调整它的大小。它将在后端使用一个数组,与真实数组的性能差异可以忽略不计。(原始数组除外)