何时在Java中使用List的数组? [英] When to use a List over an Array in Java?

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

问题描述

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

解决方案

我看到问题相反 -



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



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



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



注意:您还应该考虑一下Set(或其他数据结构)是否比List更适合您尝试做的事情。 >

每个数据结构和隐含都有不同的利弊。选择那些你需要做的事情。



如果您需要get()为O(1)任何项目?可能使用一个ArrayList,需要O(1)insert()?可能是链接列表。需要O(1)包含()?可能是一个Hashset。



TLDR:每个数据结构在某些事情上都很好,对他人来说是坏的。查看您的目标并选择最适合给定问题的数据结构。



编辑:



<一个没有注意到的事情是,你的
更好地将变量声明为
的接口(即List或Queue)
而不是其实现类。
这样,您可以在稍后的
更改
实现,而不需要更改
代码中的其他任何内容。



例如:




 列表< String> myList = new ArrayList< String>(); 




vs




 列表< String> myList = new LinkedList< String>(); 




请注意,myList是两个示例中的列表。
- R。 Bemrose



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

解决方案

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.

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.

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.

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.

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

这篇关于何时在Java中使用List的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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