Collection Family Set (six): HashSet

HashSet implements the Set is a collection of hash, which is inherited AbstractSet abstract class and implements the Set interface.

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable

principle

To understand HashSet principle, we will class member variables, constructors, two core methods introduced one by one.

Class member variables

// HashSet内部使用HashMap存储
private transient HashMap<E,Object> map;
// 存储在value上的值
private static final Object PRESENT = new Object();

From the class member variables we can know, use HashSet HashMap internal storage, while the PRESENT value is stored in all the key. So for HashSet, all of its key value are the same.

Construction method

A total of five HashSet constructor.

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);
}
    
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

We can see the constructor argument passed is actually used to initialize HashMap objects, mainly: initialCapacity (initial size), loadFactor (expansion factor). These configuration parameters are not complicated, it does not go into detail here.

There is a critical detail, i.e., a fifth method uses LinkedHashMap implemented, rather than implemented HashMap. And we want to address later LinkedHashSet is actually implemented using LinkedHashMap, which holds the insertion sequence elements.

The core method

For HashSet, its core methods are: add, remove.

We look at the add method.

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

We can see the add method to directly call the put method of HashMap object. If the Set collection insert is successful, it returns true, otherwise false.

Then we look at the remove method.

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

You can see directly call the remove method remove method HashMap object. If you delete successfully, it returns true, otherwise false.

to sum up

HashSet source code is very simple, which is directly borrowed achieve a HashMap. So if you understand the HashMap, HashSet so naturally goes without saying.

Guess you like

Origin www.cnblogs.com/chanshuyi/p/java_collection_06_hash_set.html