HashSet and LinkedHashSet source code analysis, could be so simple!

HashSetIt is not a duplicate elements may store the container, the underlying implementation dependent  , so add, delete, time complexity of lookup elements are O (1).HashMap 

The method of construction, the internal initializationHashMap

public HashSet() {
  map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
  map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
  addAll(c);
}
public HashSet(int initialCapacity, float loadFactor) {
  map = new HashMap<>(initialCapacity, loadFactor);
}

public HashSet(int initialCapacity) {
  map = new HashMap<>(initialCapacity);
}

Based approach

add 

Since HashSet only store a single value, therefore, it is internally Key, private static final Object PRESENT = new Object();is the value stored in the HashMap.

When there is no time element, it returns true, already exists, returns false.

public boolean add(E e) {
  return map.put(e, PRESENT)==null;
}

remove

public boolean remove(Object o) {
  return map.remove(o)==PRESENT;
}

clear

public void clear() {
  map.clear();
}

isEmpty

public boolean isEmpty() {
  return map.isEmpty();
}

contains 

Is determined in the HashMap exists or not Key, Key can be NULL

public boolean contains(Object o) {
  return map.containsKey(o);
}

iterator

public Iterator<E> iterator() {
  return map.keySet().iterator();
}

LinkedHashSet 继承 HashSet

Constructor:

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
  map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

public LinkedHashSet(int initialCapacity) {
  super(initialCapacity, .75f, true);
}
public LinkedHashSet() {
  super(16, .75f, true);
}

So, LinkedHashSet or use  LinkedHashMap  implemented.

to sum up

HashSetThat it is,  a simple package basis, because the characteristics of which do not need to deliberately shield some features, such as  .HashMap SetputIfAbsent

In this way we can ensure that the data type Set, but does not guarantee internal order. After all, hash is not orderly. So, still we have to look at  the source code ah.HashMap 

Author: Dian Pz

https://www.cnblogs.com/panzi/p/10854764.html

Published 50 original articles · won praise 1628 · Views 2.03 million +

Guess you like

Origin blog.csdn.net/zl1zl2zl3/article/details/104610685