java 数组的好处

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2843928/
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-10-29 23:06:34  来源:igfitidea点击:

Benefits of arrays

javaarrayslistarraylist

提问by Vitalii Fedorenko

As I see it, the advantages of a list over an array are pretty obvious:

在我看来,列表相对于数组的优势非常明显:

  • Generics provide more precise typing: List<Integer>, List<? extends Number>, List<? super Integer>.
  • A List interface has a bunch useful methods: addAll, removeetc. While for arrays all standard operations except get/set must be performed in a procedure manner by passing it to a static method.
  • Collections offer different implementations like ArrayList, LinkedList, unmodifieable and synchronized lists, which can be hidden under a common List interface.
  • OOB length control.
  • 泛型提供更精确的类型:List<Integer>, List<? extends Number>, List<? super Integer>.
  • 甲List接口有一堆有用的方法:addAllremove等等。虽然对阵列除了获取/设置所有标准操作必须在过程中的方式通过将它传递给一个静态方法进行。
  • 集合提供了不同的实现,例如ArrayListLinkedList、不可修改和同步列表,它们可以隐藏在一个公共 List 接口下。
  • OOB 长度控制。

As disadvantages I can only mention the absence of syntactic sugar and a runtime type check. At the same time supporting of both structures requires frequent using of asListand toArraymethods, which makes code less readable. So I am curious if there are any important benefits of using arrays that I miss.

作为缺点,我只能提到没有语法糖和运行时类型检查。同时支持这两种结构需要频繁使用ofasListtoArray方法,这使得代码可读性较差。所以我很好奇使用我想念的数组是否有任何重要的好处。

采纳答案by markusk

Arrays are more efficient, both in terms of processing time and memory footprint. This particularly applies if you are operating on primitive types, such as intor long, since Listrequires all elements to be wrapped in an Object(such as Integeror Long). While the autoboxing features introduced by Java 5 reduces the amount of code you need for such wrapping and unwrapping, it does not remove the performance issues, as wrapper objects are still being created.

数组在处理时间和内存占用方面都更高效。这尤其适用如果要在原始类型,例如操作intlong,由于List需要将包装在所有元素Object(如IntegerLong)。虽然 Java 5 引入的自动装箱功能减少了此类包装和解包所需的代码量,但它并没有消除性能问题,因为包装器对象仍在创建中。

However, most applications probably do not have any performance bottlenecks related to these issues, so in most cases, Listand other collections should do fine. In these cases, the ease of programming outweighs the increase in memory or CPU usage, and Listis the right choice.

但是,大多数应用程序可能没有与这些问题相关的任何性能瓶颈,因此在大多数情况下,List其他集合应该可以正常工作。在这些情况下,编程的简便性超过了内存或CPU使用率的增加,List是正确的选择。

回答by unholysampler

If your list does not change often, Lists add lots of extra weight to the object that you will never use. When you are trying to run something that needs to be optimized, this is helpful. This extra weight also makes things slower than they would be with just arrays. However, unless you know that you need the gains arrays give you, you should just be using Lists.

如果您的列表不经常更改,则列表会为您永远不会使用的对象增加许多额外的重量。当您尝试运行需要优化的东西时,这很有帮助。这种额外的重量也使事情比仅使用数组时要慢。然而,除非你知道你需要数组给你的增益,否则你应该只使用列表。

回答by Guillaume

One thing I have not seen mentioned here: arrays can have N dimensions whereas lists are limited to one. You can use lists of lists but the syntax (List<List<...>>) is much more cumbersome than [][]

我在这里没有看到的一件事是:数组可以有 N 维,而列表仅限于一维。您可以使用列表列表,但语法 ( List<List<...>>) 比 [][] 复杂得多

回答by doublep

Speed. Collections are somewhat slower than simple arrays: internally most still use arrays, but have additional layers of code around those. Of course, unless you have specific need for extra performance, you should still use collections.

速度。集合比简单的数组慢一些:内部大多数仍然使用数组,但在这些数组周围有额外的代码层。当然,除非您特别需要额外的性能,否则您仍然应该使用集合。

Another smallish advantage of arrays is that it mightbe easier to call variadic methods with arrays. This should never be a main reason to pick one over another though.

数组的另一个小优势是使用数组调用可变参数方法可能更容易。不过,这永远不应成为选择一个的主要原因。

回答by Norman Ramsey

If there are any important benefits of using arrays that I miss?

如果我想念使用数组有什么重要的好处吗?

Constant-time access to any elementwith a very small constant. To access an array element safely takes just a few instructions: a couple of loads, a compare, and a branch. The branch is typically successful nearly 100% of the time, so modern hardware does an excellent job predicting it.

常量时间访问任何具有非常小的常量的元素。要安全地访问数组元素只需要几条指令:几次加载、一次比较和一次分支。该分支通常几乎 100% 的时间都是成功的,因此现代硬件在预测它方面做得非常出色。

回答by Doobi

I guess the theoretical answer is that array are supposed to have better performance because Generic collections have additional layers of abstraction. Personally, in a business app, I see very little value in using Arrays over generic collections.

我想理论上的答案是数组应该有更好的性能,因为泛型集合有额外的抽象层。就个人而言,在商业应用程序中,我认为在泛型集合上使用数组的价值很小。

回答by Eyal Schneider

In addition to the other responses, there is one subtle property of arrays that can be considered an advantage over lists. It can be illustrated by the following code:

除了其他响应之外,数组还有一个微妙的属性,可以被认为是优于列表的。可以用下面的代码来说明:

//This works
Integer[] ints = new Integer[4];
Number[] nums = ints;
//This doesn't work
List<Integer> intList = new ArrayList<Integer>();
List<Number> numList = intList; //Does not compile
List<Number> numList2 = (List<Number>)intList; //Does not compile either

While an array of a subclass IS an array of the superclass, lists of subclasses are NOT lists of superclasses (and there is a good reason for it - generics would have a type safery flaw if it were allowed).

虽然子类的数组是超类的数组,但子类的列表不是超类的列表(并且有一个很好的理由 - 如果允许,泛型将具有类型安全缺陷)。

回答by Leni Kirilov

Arrays are better in the following situations:

数组在以下情况下更好:

  • you know that you will work with fixed number of elements in the array
  • you don't need to change size of the array
  • 你知道你将使用数组中固定数量的元素
  • 你不需要改变数组的大小

Arrays are:

数组是:

  • faster than any Collection
  • 比任何集合都快


Collections similar to Array:

类似于 Array 的集合:

  • ArrayList- fast read and add to the end of the List. Uses internally array. Slow if you have to increase the size of the List
  • LinkedList- fast add to both sides of the List. Fast dynamic size increase/decrease. Doesn't use internally array
  • ArrayList- 快速阅读并添加到List. 使用内部数组。如果您必须增加大小,则缓慢List
  • LinkedList- 快速添加到两边List。快速动态大小增加/减少。不使用内部数组


Conclusion:

结论:

I recommend to use the appropriate for your scenario Collection. Don't struggle with Array []because the Collectionspackage offers very comfortable API like add(), addAll()etc.

我建议使用适合您场景的 Collection。不要挣扎Array [],因为Collections包提供了非常舒适的API一样add()addAll()等等。



Reference: You can find a more detailed comparison here -> "Arrays vs ArrayList vs LinkedList vs..."

参考:您可以在此处找到更详细的比较 -> “Arrays vs ArrayList vs LinkedList vs...”

回答by Michael Aaron Safyan

It really depends on the situation. Arrays are incredibly fast, but they are a fixed size and they may not be suitable if the amount of data that you need to process is very large. Collections, on the other hand, have varying degrees of performance, depending on the particular subclass. The ArrayList, for example, is mostly just a wrapper around an array and so should have similar iteration speed and memory requirements. For myself, I typically use the Iterable<T> interface wherever possible, since that gives the greatest flexibility to my code, allowing it to process in-memory resident arrays as well as lists of data that are fetched from a file or over a network using a custom iterable/iterator class. When it is time to actually instantiate the Iterable object that I pass-in, that depends on the specific situation; if I know the size and it will fit in memory at once, then I simply use an array, while if it will possibly grow, then I will use an ArrayList, and if it needs fast insertion at both ends, then I will use a LinkedList.

这真的取决于情况。数组非常快,但它们的大小是固定的,如果您需要处理的数据量非常大,它们可能不适合。另一方面,集合具有不同程度的性能,具体取决于特定的子类。例如,ArrayList 主要只是一个数组的包装器,因此应该具有相似的迭代速度和内存要求。对于我自己,我通常尽可能使用 Iterable<T> 接口,因为这为我的代码提供了最大的灵活性,允许它处理内存中的常驻数组以及从文件或通过网络获取的数据列表使用自定义的可迭代/迭代器类。何时真正实例化我传入的 Iterable 对象,这取决于具体情况;