HashSet和LinkedHashSet

时间:2013-08-27 14:08:17

标签: java collections hashset insertion linkedhashset

所以我正在开发一个程序,我需要存储原始类型的唯一客户数据。在这方面,我一直在阅读一本关于数据结构的书,并得出结论使用HashSet

现在,本书指出HashSet的插入和删除速度比LinkedHashSet更快。现在这让我感到困惑。我认为两者之间的唯一区别是,LinkedHashSet使用了一些额外的内存,使用LinkedList来保持秩序。

任何人都可以详细说明吗?

2 个答案:

答案 0 :(得分:4)

Java中的TreeSet,LinkedHashSet和HashSet是集合框架中的三个Set实现,与许多其他实现一样,它们也用于存储对象。 TreeSet的主要特征是排序,LinkedHashSet是插入顺序,HashSet只是用于存储对象的通用集合。 HashSet是使用Java中的HashMap实现的,而TreeSet是使用TreeMap实现的。 TreeSet是一个SortedSetimplementation,它允许它按照Comparable或Comparator接口定义的排序顺序保留元素。 Comparable用于自然顺序排序和Comparator,用于对象的自定义顺序排序,可以在创建TreeSet实例时提供。无论如何,在看到TreeSet,LinkedHashSet和HashSet之间的区别之前,让我们看看它们之间有一些相似之处:

1)重复:所有三个实现Set接口意味着它们不允许存储重复项。

2)线程安全:HashSet,TreeSet和LinkedHashSet不是线程安全的,如果你在多线程环境中使用它们,其中至少有一个线程修改了Set,你需要在外部同步它们。

3)Fail-Fast Iterator:TreeSet返回的迭代器,LinkedHashSet和HashSet是故障快速迭代器。即如果Iterator在创建之后通过除Iterators remove()方法以外的任何方式进行修改,则会尽力抛出ConcurrentModificationException。阅读更多关于故障快速与故障安全迭代器的信息

现在让我们看看Java中的HashSet,LinkedHashSet和TreeSet之间的区别:

性能和速度:它们之间的第一个区别在于速度。 HashSet是最快的,LinkedHashSet在性能上排名第二或几乎与HashSet类似,但TreeSet因为每次插入时需要执行的排序操作而有点慢。 TreeSet为诸如add,remove和contains之类的常见操作提供了保证的O(log(n))时间,而HashSet和LinkedHashSet提供了恒定的时间性能,例如: O(1)用于添加,包含和删除给定的哈希函数,在桶中均匀分布元素。

Ordering:HashSet不维护任何顺序,而LinkedHashSet维护元素的插入顺序很像List接口,TreeSet维护排序顺序或元素。

内部实现:HashSet由HashMap实例支持,LinkedHashSet使用HashSet和LinkedList实现,而TreeSet由Java中的NavigableMap备份,默认情况下使用TreeMap。

null:HashSet和LinkedHashSet都允许null但TreeSet不允许null但TreeSet不允许null并且当您将null插入TreeSet时抛出java.lang.NullPointerException。由于TreeSet使用各个元素的compareTo()方法来比较它们在与null比较时抛出NullPointerException,这里是

答案 1 :(得分:3)

明智地选择数据结构。

如果插入顺序对您很重要,您可以使用Linked Hash Set而不是Hash Set。使用其他功能,内存或处理器周期可能会受到影响。

编辑1: 除了插入顺序之外还要考虑的事项:因为LinkedHashSet保持双重链接列表,插入和删除会更慢,但迭代时会稍微快一些。

引用java doc:

This class provides all of the optional Set operations, and permits null elements. Like HashSet, it provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list, with one exception: Iteration over a LinkedHashSet requires time proportional to the size of the set, regardless of its capacity. Iteration over a HashSet is likely to be more expensive, requiring time proportional to its capacity.

相关问题