List 和 Set 的性能和内存分配比较

2022-01-17 00:00:00 list set collections java

我想知道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.

相关文章