Java的HashSet的VS阵列性能 [英] Java HashSet vs Array Performance

查看:145
本文介绍了Java的HashSet的VS阵列性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有保证是不同对象的集合(特别是由一个唯一的整数ID索引)。我也知道到底多少人有(和数量不会改变),并想知道阵列是否有超过HashSet的一个显着的性能优势,用于存储/检索所述元件。

I have a collection of objects that are guaranteed to be distinct (in particular, indexed by a unique integer ID). I also know exactly how many of them there are (and the number won't change), and was wondering whether Array would have a notable performance advantage over HashSet for storing/retrieving said elements.

在纸上,阵列保证恒定的时间插入(因为我事先知道的大小)和检索,但code代表的HashSet看起来清爽多了,并增加了一些灵活性,所以我想知道如果我失去了什么性能明智的使用它,至少在理论上。

On paper, Array guarantees constant time insertion (since I know the size ahead of time) and retrieval, but the code for HashSet looks much cleaner and adds some flexibility, so I'm wondering if I'm losing anything performance-wise using it, at least, theoretically.

推荐答案

取决于你的数据;

HashSet的为您提供了一个 O(1) contains()方法,但没有preserve秩序

HashSet gives you an O(1) contains() method but doesn't preserve order.

的ArrayList 包含()的 O(N),但你可以控制项的顺序。

ArrayList contains() is O(n) but you can control the order of the entries.

阵列如果你需要在这两者之间塞入任何东西,最坏的情况可能是为O(n),因为你将不得不向下移动数据,并腾出空间插入。在设置,您可以直接使用的SortedSet这也为O(n)的太多,但具有灵活操作。

Array if you need to insert anything in between, worst case can be O(n), since you will have to move the data down and make room for the insertion. In Set, you can directly use SortedSet which too has O(n) too but with flexible operations.

我相信设置更加灵活。

这篇关于Java的HashSet的VS阵列性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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