List和Set的性能和内存分配对比 [英] Performance and Memory allocation comparison between List and Set

查看:44
本文介绍了List和Set的性能和内存分配对比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道List和Set在性能、内存分配和可用性方面的比较.

I want to know the comparison between List and Set in terms of performance,memory allocation and usability.

如果我不需要在对象列表中保持唯一性,也不需要维护插入顺序,我可以互换使用 ArrayList 和 SortedSet/HashSet 吗?直接使用 Collections 类而不是 list/set 会好吗?

If i don't have any requirement of keeping the uniqueness in the list of objects, neither required the insertion order to be maintained, Can I use ArrayList and SortedSet/HashSet interchangeably? Will it be good to directly use Collections class instead of even list/set?

附言我也不需要列出或设置 java 提供的特定功能.我使用 List/Set 而不是 Array 只是因为它们可以在没有额外编程工作的情况下动态增长.

P.S. I also don't have any need for list or set specific functions provided by java. I am using List/Set instead of Array only because they can dynamically grow without extra programming efforts.

推荐答案

如果你不关心排序,不删除元素,那真的归结为你是否需要在这个数据结构中查找元素,以及您需要多快的查找速度.

If you don't care about the ordering, and don't delete elements, then it really boils down to whether you need to find elements in this data structure, and how fast you need those lookups to be.

通过 HashSet 中的值查找元素是 O(1).在 ArrayList 中,它是 O(n).

Finding an element by value in a HashSet is O(1). In an ArrayList, it's O(n).

如果你只使用容器来存储一堆独特的对象,并在最后迭代它们(以任何顺序),那么可以说 ArrayList 是更好的选择,因为它更简单,更多经济实惠.

If you are only using the container to store a bunch of unique objects, and iterate over them at the end (in any order), then arguably ArrayList is a better choice since it's simpler and more economical.

这篇关于List和Set的性能和内存分配对比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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