当使用列表上Java中的数组? [英] When to use a List over an Array in Java?

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

问题描述

在Java中,何时会是被preferential使用一个列表,而不是一个数组?


解决方案

我看到了一个问题,作为opposite-

当你应该使用一个列表数组?

只有你有一个具体的理由这样做(例如:项目的限制,内存的担忧(不是真的一个很好的理由)等)

列表是更容易使用(IMO),并有更多的功能。

请注意:你也应该考虑是不是像一个集或其他数据结构比列表,更好地适应你正在尝试做的。

每个数据结构,并implmentation,都有不同的优点/缺点。挑选一个擅长,你需要做的事情的人。

如果你需要得到()是O(1)任何项目?可能使用ArrayList,需要O(1)插入()?可能是一个链表。需要O(1)包括()?可能HashSet的。

TLDR:每个数据结构是擅长一些事情,坏别人。看看你的目标,并选择最适合给定问题的数据结构。

编辑:


  

没有注意到的一件事是你
  更好声明变量
  它的界面(即列表或队列)
  而不是它的实现类。
  通过这种方式,您可以更改
  实现在以后的日期
  而不在不断变化的其他任何
  code。


  
  

作为一个例子:


 列表<串GT; myList中=新的ArrayList<串GT;();


  

VS


 列表<串GT; myList中=新的LinkedList<串GT;();


  

注意myList上是在这两个例子的List。
   - 研究。 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中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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