数组的好处 [英] Benefits of arrays

查看:36
本文介绍了数组的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  • 泛型提供更精确的类型:List, List,列表.
  • List 接口有很多有用的方法:addAllremove 等.而对于数组,除了 get/set 之外的所有标准操作都必须通过传递以过程方式执行将其转换为静态方法.
  • Collections 提供了不同的实现,例如 ArrayListLinkedList、不可修改和同步的列表,它们可以隐藏在一个通用的 List 接口下.
  • OOB 长度控制.
  • Generics provide more precise typing: List<Integer>, List<? extends Number>, List<? super Integer>.
  • A List interface has a bunch useful methods: addAll, remove etc. 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.

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

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 asList and toArray methods, which makes code less readable. So I am curious if there are any important benefits of using arrays that I miss.

推荐答案

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

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 int or long, since List requires all elements to be wrapped in an Object (such as Integer or 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.

然而,大多数应用程序可能不存在与这些问题相关的任何性能瓶颈,因此在大多数情况下,List 和其他集合应该没问题.在这些情况下,编程的简易性大于内存或 CPU 使用率的增加,List 是正确的选择.

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

这篇关于数组的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆