为什么在 Java 中更喜欢使用列表而不是数组? [英] Why is it preferred to use Lists instead of Arrays in Java?

查看:29
本文介绍了为什么在 Java 中更喜欢使用列表而不是数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多人和作者建议我们使用列表而不是数组.

Many people and authors suggested to us to use list than array.

List <Integer> list = new ArrayList<Integer>();
list.addElement(1);
....

这背后的原因是什么?

推荐答案

通常您应该更喜欢为工作选择正确的数据结构.您需要了解您手头的任务以及您拥有的所有不同选项,以及它们如何在迭代、搜索、添加、删除和插入数据方面进行比较.一般来说,您需要了解数据结构如何访问和操作内存,并根据您预期应用程序的使用方式选择最佳数据结构.

You should generally prefer to choose the right data structure for the job. You need to understand your task at hand as well as all the different options you have and how they compare in terms of iteration, and searching, and adding, removing, and inserting data. In general, you need to understand how the data structure accesses and manipulates memory and choose the best data structure based on how you anticipate your application will be used.

显然,它并不总是明确的.但是你可以理解不同数据结构的理想.

Obviously, it isn't always clear-cut. But you can understand the ideals for different data structures.

例如,纯静态、固定长度的数据,您只需要迭代,不需要搜索,是数组的理想选择.在密码算法中使用这样的数组是很常见的.如果数据是静态的但不是迭代,您需要搜索,您可能需要某种类型的树结构.如果你想要快速插入,散列可能是理想的.如果数据经常变化,您需要一个能有效改变其大小的结构,如列表.

For example, purely static, fixed length data in which you'll only iterate, without a need for search, is ideal for an array. It's common to use such arrays in cipher algorithms. If the data is static but instead of iterating, you need to search, you might want some type of tree structure. If you want fast insertion, hashing is probably the ideal. If the data changes often, you want a structure that is efficient at changing its size, like a list.

当然,数据结构有许多变体和组合,旨在解决各种特定问题.之所以有这么多,是因为它们在编写高效程序方面发挥着重要作用.无论如何,我的观点是,学习数据结构.了解每种情况的理想情况,然后您就能够为任何任务决定或设计合适的数据结构.

Of course, there's many variations and combinations of data structures designed to solve all kinds of specific problems. The reason there are so many is because of the importance they play in writing efficient programs. Anyway, my point is, learn about data structures. Understand the ideal situations for each and then you'll be able to decide or design suitable data structures for any task.

这篇关于为什么在 Java 中更喜欢使用列表而不是数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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