HashSet 和 TreeSet 区别 、 HashSet的底层

不念不忘少年蓝@ 2023-03-01 10:58 86阅读 0赞

HashSet

HashSet是依靠hash table实现的(内部实现实际上是一个HashMap)。 不保证顺序(hash无法保证顺序)。 允许null值。 因为其实现借助于hash表,所以两个元素,e1.equals(e2),必须也要保证 e1.hashCode() == e2.hashCode()

LinkedHashSet

LinkedHashSet继承自HashSet,不过和HashSet不同的是,它是借助于LinkedHashMap实现的(LinkedHashMap其实也继承自HashMap,但是它依靠双向链表,实现了插入顺序有序)。所以它的特性和HashSet类似,但是LinkedHashSet是有序的,因为有了链表,所以在遍历元素的时候LinkedHashSet要优于HashSet,但是在插入时,增加了维护链表的开销,所以插入性能略差于HashSet。

  1. /** * 依靠Hash table和linked list实现的set集合,支持顺序。 * 和HashSet的区别是内部维护了一个双向链表,链表的顺序就是插入的顺序。 * 当一个元素重新插入set时,其内部顺序不受影响 */
  2. public class LinkedHashSet<E>
  3. extends HashSet<E>
  4. implements Set<E>, Cloneable, java.io.Serializable

TreeSet

不同与HashSet的无序,LinkedHashSet的插入有序,TreeSet是有序的集合,其实现了SortedSet接口。TreeSet借助于TreeMap实现。Set内的元素按照 Comparable 或者 传入构造器的Comparator的顺序排序。TreeSet不支持null元素(因为要排序嘛)。

源码分析

HashSet

HashSet的构造函数初始化,实质上底层新建了一个HashMap的对象,可以参照之前的文章JDK8 HashMap源码详解 HashMap的构造函数对照着一起看。

  1. /**
  2. * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
  3. * default initial capacity (16) and load factor (0.75).
  4. */
  5. public HashSet() {
  6. map = new HashMap<>();
  7. }
  8. /**
  9. * Constructs a new set containing the elements in the specified
  10. * collection. The <tt>HashMap</tt> is created with default load factor
  11. * (0.75) and an initial capacity sufficient to contain the elements in
  12. * the specified collection.
  13. *
  14. * @param c the collection whose elements are to be placed into this set
  15. * @throws NullPointerException if the specified collection is null
  16. */
  17. public HashSet(Collection<? extends E> c) {
  18. map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
  19. addAll(c);
  20. }
  21. /**
  22. * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
  23. * the specified initial capacity and the specified load factor.
  24. *
  25. * @param initialCapacity the initial capacity of the hash map
  26. * @param loadFactor the load factor of the hash map
  27. * @throws IllegalArgumentException if the initial capacity is less
  28. * than zero, or if the load factor is nonpositive
  29. */
  30. public HashSet(int initialCapacity, float loadFactor) {
  31. map = new HashMap<>(initialCapacity, loadFactor);
  32. }
  33. /**
  34. * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
  35. * the specified initial capacity and default load factor (0.75).
  36. *
  37. * @param initialCapacity the initial capacity of the hash table
  38. * @throws IllegalArgumentException if the initial capacity is less
  39. * than zero
  40. */
  41. public HashSet(int initialCapacity) {
  42. map = new HashMap<>(initialCapacity);
  43. }
  44. /**
  45. * Constructs a new, empty linked hash set. (This package private
  46. * constructor is only used by LinkedHashSet.) The backing
  47. * HashMap instance is a LinkedHashMap with the specified initial
  48. * capacity and the specified load factor.
  49. *
  50. * @param initialCapacity the initial capacity of the hash map
  51. * @param loadFactor the load factor of the hash map
  52. * @param dummy ignored (distinguishes this
  53. * constructor from other int, float constructor.)
  54. * @throws IllegalArgumentException if the initial capacity is less
  55. * than zero, or if the load factor is nonpositive
  56. */
  57. HashSet(int initialCapacity, float loadFactor, boolean dummy) {
  58. map = new LinkedHashMap<>(initialCapacity, loadFactor);
  59. }

到这里,并不能明确HashSet传入的数据是用什么规则去插入到HashMap的,那么开始看看HashSet的add() 方法,这里有一个静态final参数PRESENT,按照源码中的释义是一个伪值,方便映射对象关联的。

  1. // Dummy value to associate with an Object in the backing Map
  2. private static final Object PRESENT = new Object();

而这个伪值则用来在HashSet 新增时,作为底层HashMap的Value插入。到这里也不难理解为什么HashSet中的数据不能重复的原因了,存入的值,通过计算HashCode寻址,作为链表node 的属性key存入到HashMap 中去。

  1. /**
  2. * Adds the specified element to this set if it is not already present.
  3. * More formally, adds the specified element <tt>e</tt> to this set if
  4. * this set contains no element <tt>e2</tt> such that
  5. * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
  6. * If this set already contains the element, the call leaves the set
  7. * unchanged and returns <tt>false</tt>.
  8. *
  9. * @param e element to be added to this set
  10. * @return <tt>true</tt> if this set did not already contain the specified
  11. * element
  12. */
  13. public boolean add(E e) {
  14. return map.put(e, PRESENT)==null;
  15. }

其它的一些操作也都是和HashMap中的操作存在有对应的关系,也没太多好说的,可以将HashSet中的操作方法与HashMap源码中操作的方法对照起来看。

  1. /**
  2. * Returns an iterator over the elements in this set. The elements
  3. * are returned in no particular order.
  4. *
  5. * @return an Iterator over the elements in this set
  6. * @see ConcurrentModificationException
  7. */
  8. public Iterator<E> iterator() {
  9. return map.keySet().iterator();
  10. }
  11. /**
  12. * Returns the number of elements in this set (its cardinality).
  13. *
  14. * @return the number of elements in this set (its cardinality)
  15. */
  16. public int size() {
  17. return map.size();
  18. }
  19. /**
  20. * Returns <tt>true</tt> if this set contains no elements.
  21. *
  22. * @return <tt>true</tt> if this set contains no elements
  23. */
  24. public boolean isEmpty() {
  25. return map.isEmpty();
  26. }
  27. /**
  28. * Returns <tt>true</tt> if this set contains the specified element.
  29. * More formally, returns <tt>true</tt> if and only if this set
  30. * contains an element <tt>e</tt> such that
  31. * <tt>(o==null ? e==null : o.equals(e))</tt>.
  32. *
  33. * @param o element whose presence in this set is to be tested
  34. * @return <tt>true</tt> if this set contains the specified element
  35. */
  36. public boolean contains(Object o) {
  37. return map.containsKey(o);
  38. }
  39. /**
  40. * Removes the specified element from this set if it is present.
  41. * More formally, removes an element <tt>e</tt> such that
  42. * <tt>(o==null ? e==null : o.equals(e))</tt>,
  43. * if this set contains such an element. Returns <tt>true</tt> if
  44. * this set contained the element (or equivalently, if this set
  45. * changed as a result of the call). (This set will not contain the
  46. * element once the call returns.)
  47. *
  48. * @param o object to be removed from this set, if present
  49. * @return <tt>true</tt> if the set contained the specified element
  50. */
  51. public boolean remove(Object o) {
  52. return map.remove(o)==PRESENT;
  53. }
  54. /**
  55. * Removes all of the elements from this set.
  56. * The set will be empty after this call returns.
  57. */
  58. public void clear() {
  59. map.clear();
  60. }

发表评论

表情:
评论列表 (有 0 条评论,86人围观)

还没有评论,来说两句吧...

相关阅读

    相关 TreeSetHashSet

    目录   TreeSet 1、特性 2、通过构造方法自定义排序规则  3、通过包装达到线程安全 4、TreeSet 迭代 5、关于是否可以保存null 元素 H