Javaデータ型シリーズのHashSet

1.HashSetの最初の知人

HashSetは、JavaコレクションSetの実装クラスです。Setはインターフェイスです。HashSetに加えて、TreeSetもあり、Collectionを継承します。HashSetコレクションは非常に一般的に使用され、プログラマーがインタビュー中によく尋ねる知識でもあります。ポイント、以下は構造図です

Javaデータ型シリーズのHashSet

 

それでもいつものようにクラスの注釈を見てください

/**
 * This class implements the <tt>Set</tt> interface, backed by a hash table (actually a <tt>HashMap</tt> instance).  It makes no guarantees as to the iteration order of the set; 
 * in particular, it does not guarantee that the order will remain constant over time.  This class permits the <tt>null</tt> element.
 * 这个类实现了set 接口,并且有hash 表的支持(实际上是HashMap),它不保证集合的迭代顺序
 * This class offers constant time performance for the basic operations(<tt>add</tt>, <tt>remove</tt>, <tt>contains</tt> and <tt>size</tt>),
 * assuming the hash function disperses the elements properly among the buckets.  
 * 这个类的add remove contains 操作都是常数级时间复杂度的
 * Iterating over this set requires time proportional to the sum of the <tt>HashSet</tt> instance's size (the number of elements) plus the
 * "capacity" of the backing <tt>HashMap</tt> instance (the number of buckets).  
 * 对此集合进行迭代需要的时间是和该集合的大小(集合中存储元素的个数)加上背后的HashMap的大小是成比列的
 * Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
 * 因此如果迭代的性能很重要,所以不要将初始容量设置的太大(因为这意味着背后的HashMap会很大)
 * <p><strong>Note that this implementation is not synchronized.</strong> If multiple threads access a hash set concurrently, 
 * and at least one ofthe threads modifies the set, it <i>must</i> be synchronized externally.
 * 注意次集合没有实现同步,如果多个线程并发访问,并且至少有一个线程会修改,则必须在外部进行同步(加锁)
 * This is typically accomplished by synchronizing on some object that naturally encapsulates the set.
 * 通常在集合的访问集合的外边通过对一个对象进行同步实现(加锁实现)
 * If no such object exists, the set should be "wrapped" using the @link Collections#synchronizedSet Collections.synchronizedSet} ethod.  
 * 如果没有这样的对象,可以尝试Collections.synchronizedSet 方法对set 进行封装(关于Collections工具类我单独写了一篇,可以自行查看)
 * this is best done at creation time, to prevent accidental unsynchronized access to the set:<pre> Set s = Collections.synchronizedSet(new HashSet(...));</pre>
 * 这个操作最好是创建的时候就做,防止意外没有同步的访问,就像这样使用即可 Set s = Collections.synchronizedSet(new HashSet(...))
 * <p>The iterators returned by this class's <tt>iterator</tt> method are <i>fail-fast</i>: if the set is modified at any time after the iterator is
 * created, in any way except through the iterator's own <tt>remove</tt> method, the Iterator throws a {@link ConcurrentModificationException}.
 * 这一段我们前面也解释过很多次了关于fail-fast 我们不解释了(可以看ArrayList 一节)
 * Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the
 * presence of unsynchronized concurrent modification.  Fail-fast iterators
 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
 * Therefore, it would be wrong to write a program that depended on this exception for its correctness: <i>the fail-fast behavior of iterators should be used only to detect bugs.</i>
 * 
 * @author  Josh Bloch
 * @author  Neal Gafter
 * @see     Collection
 * @see     HashMap
 * @since   1.2
 */

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

1.HashSetの構築方法


まず、全体を見ていきましょう。以下の工法を一つずつ見ていきます。

private transient HashMap<E,Object> map;
//默认构造器
public HashSet() {
    map = new HashMap<>();
}
//将传入的集合添加到HashSet的构造器
public HashSet(Collection<? extends E> c) {
    map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
    addAll(c);
}
//仅明确初始容量的构造器(装载因子默认0.75)
public HashSet(int initialCapacity) {
    map = new HashMap<>(initialCapacity);
}

//明确初始容量和装载因子的构造器
public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
}
// 
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

次のソースコードを読み、クラスアノテーションを理解することにより、HashSetは革製バッグ会社であることがわかりました。外部作業を行い、受信時にHashMapに直接スローします。最下層はHashMapを介して実装されているため、ここで簡単に説明します。

HashMapのデータストレージは、配列+リンクリスト/赤黒木によって実現されます。おおよそのストレージプロセスは、ハッシュ関数を使用して配列内のストレージ位置を計算することです。位置にすでに値がある場合は、キーかどうかが判断されます。が同じ、同じが上書きされる、同じではない要素に対応するリンクリストに入れます。リンクリストの長さが8より大きい場合、赤黒木に変換されます。容量が十分ではありません。拡張する必要があります(注:これは単なる一般的なプロセスです)。

パラメータなしの構築


デフォルトのコンストラクターは、最も一般的に使用されるコンストラクターでもあります

/**
 * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has default initial capacity (16) and load factor (0.75).
 * 创建一个新的、空的set, 背后的HashMap实例用默认的初始化容量和加载因子,分别是16和0.75
 */
public HashSet() {
    map = new HashMap<>();
}

セットベースの建設

/**
 * Constructs a new set containing the elements in the specified collection.  The <tt>HashMap</tt> is created with default load factor (0.75) and 
 * an initial capacity sufficient to contain the elements in the specified collection.
 *  创建一个新的包含指定集合里面全部元素的set,背后的HashMap 依然使用默认的加载因子0.75,但是初始容量是足以容纳需要容纳集合的(其实就是大于该集合的最小2的指数,更多细节可以查看HashMap 那一节的文章)
 * @param c the collection whose elements are to be placed into this set
 * @throws NullPointerException if the specified collection is null 当集合为空的时候抛出NullPointerException
 */
public HashSet(Collection<? extends E> c) {
    map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
    addAll(c);
}

初期容量構造を指定します


実際、以下の3種類の構造がありますが、すべて初期容量を指定しているため、このカテゴリに分類しました。


初期容量のみが指定されています

/**
 * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has the specified initial capacity and default load factor (0.75).
 * 创建一个新的,空的集合,使用了默认的加载因子和以参数为参考的初始化容量
 * @param      initialCapacity   the initial capacity of the hash table
 * @throws     IllegalArgumentException if the initial capacity is less than zero 参数小于0的时候抛出异常
 */
public HashSet(int initialCapacity) {
    map = new HashMap<>(initialCapacity);
}

パラメータによって参照される初期容量、なぜそれがこのように表現されるのか、ハッシュマップの詳細な分析も見ることができます

/**
 * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has the specified initial capacity and the specified load factor.
 * 创建一个新的,空的集合,使用了指定的加载因子和以参数为参考的初始化容量
 * @param      initialCapacity   the initial capacity of the hash map
 * @param      loadFactor        the load factor of the hash map
 * @throws     IllegalArgumentException if the initial capacity is less  than zero, or if the load factor is nonpositive 加载因子和初始容量不合法
 */
public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
}

ダミー


これについては、後でLinkedHashSetで詳しく説明します。実際、このパラメーターはLinkedHashSetでTrueが指定され、現時点では、マップはHashMapではなくLinkedHashMapへの参照です。

/**
 * Constructs a new, empty linked hash set.  (This package private constructor is only used by LinkedHashSet.) The backing HashMap instance is a LinkedHashMap with the specified initial
 * capacity and the specified load factor.
 * 忽略 dummy 参数的话和前面一样,这个构造方法主要是在LinkedHashSet中使用,而且你看到这个时候map 不再直接是HashMap 而是 LinkedHashMap
 * @param      initialCapacity   the initial capacity of the hash map
 * @param      loadFactor        the load factor of the hash map
 * @param      dummy             ignored (distinguishes this constructor from other int, float constructor.)
 * @throws     IllegalArgumentException if the initial capacity is less
 *             than zero, or if the load factor is nonpositive
 */
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
    map = new LinkedHashMap<>(initialCapacity, loadFactor);
}

HashSetの重要な属性


地図


先に述べたように、HashSetは革のバッグ会社であり、その背後にあるビッグボス、つまり実際に仕事をしている人がいます。HashSetのすべてのデータはこのHashMapに保存されています。

private transient HashMap<E,Object> map;

現在

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

この値は少し興味深いです。これはHashMapで受け入れられるキーとキーと値のペアであるため、HashSetに要素を追加するたびに、パラメーターeとこの要素がキー値に構成されます(e-PRESENT)はい、HashMapに渡します


私の神、私はそのような恥知らずなデータ構造を見たことがありません、そして私は自分自身をHashSetと名付け、HashMapと同じレベルにし、外部でユーザーをだまし、内部でHashMapをだまし、毎回一定のデータを人々に提供します値は同じではありません卵殻として?


2.HashSetの一般的なメソッド


1.メソッドを追加します

public static void main(String[] args) {
    HashSet hashSet=new HashSet<String>();
    hashSet.add("a");
}
复制代码

HashSetのaddメソッドはHashMapのputメソッドによって実装されますが、HashMapはキーとキーと値のペアであり、HashSetはコレクションなので、どのように格納されますか?ソースコードを見てみましょう。

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

/**
 * Adds the specified element to this set if it is not already present,If this set already contains the element, the call leaves the set unchanged and returns <tt>false</tt>.
 * 添加一个 不存在的元素到集合,如果已经存在则不作改动,然后返回false
 * @param e element to be added to this set
 * @return <tt>true</tt> if this set did not already contain the specified 不存在在返回true,存在返回false
 */
public boolean add(E e) {
  	// map.put(e, PRESENT) 的返回值就是oldValue
    return map.put(e, PRESENT)==null;
}
复制代码

ソースコードを見ると、HashSetによって追加された要素はHashMapのキー位置に格納されており、値は空のオブジェクトであるデフォルトの定数PRESENTを取ります。実際、私は見ると文句を言わざるを得ません。これ。nullを与えるのは良いことではありませんか?HashMapキーと値としてnullをサポートします。さらに、ここでは値だけです。ここで同じオブジェクトPRESENTを使用していますが、現時点ではnullが正しい解決策です。

もう1つ言いたいのは、戻り値についてです。HashMap.put()メソッドの戻り値はoldValueであることがわかっていますが、もちろんnullの場合もあります。つまり、oldValueがないため、HashSetはに基づいて戻ることを決定します。 oldValueが空かどうか。値。つまり、oldValueが空でない場合は、falseを返し、すでに存在していることを示します。実際、最初に存在するかどうかを判断しない理由を考えて、追加することができます。それが存在しないときそれはより合理的ではありませんか?ようこそ議論

HashMapは、値が意味があるため、値を更新する必要があるため、存在するかどうかを判断しませんが、HashSetについてはどうでしょうか。

マップのputメソッドについては、Hashmapの詳細な分析を見ることができます。

Javaデータ型シリーズのHashSet

 

もちろん、addAll(Collection <?extends E> c)メソッドなど、addメソッドの他のバリエーションもあります。

2.removeメソッド

HashSetのremoveメソッドは、HashMapのremoveメソッドによって実装されます。

/**
 * Removes the specified element from this set if it is present. More formally, removes an element if this set contains such an element.  Returns <tt>true</tt> 
 * 如果set 中有这个元素的话,remove 操作会将它删除,通常情况下,如果存在的话返回True
 * @param o object to be removed from this set, if present 如果存在则删除
 * @return <tt>true</tt> if the set contained the specified element
 */
public boolean remove(Object o) {
  	// 调用了HashMap 的remove 方法
    return map.remove(o)==PRESENT;
}
//map的remove方法
public V remove(Object key) {
    Node<K,V> e;
    //通过hash(key)找到元素在数组中的位置,再调用removeNode方法删除
    return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;
}

final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    //步骤1.需要先找到key所对应Node的准确位置,首先通过(n - 1) & hash找到数组对应位置上的第一个node
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        //1.1 如果这个node刚好key值相同,运气好,找到了
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        /**
         * 1.2 运气不好,在数组中找到的Node虽然hash相同了,但key值不同,很明显不对, 我们需要遍历继续
         *     往下找;
         */
        else if ((e = p.next) != null) {
            //1.2.1 如果是TreeNode类型,说明HashMap当前是通过数组+红黑树来实现存储的,遍历红黑树找到对应node
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                //1.2.2 如果是链表,遍历链表找到对应node
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        //通过前面的步骤1找到了对应的Node,现在我们就需要删除它了
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            /**
             * 如果是TreeNode类型,删除方法是通过红黑树节点删除实现的,具体可以参考【TreeMap原理实现
             * 及常用方法】
             */
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            /** 
             * 如果是链表的情况,当找到的节点就是数组hash位置的第一个元素,那么该元素删除后,直接将数组
             * 第一个位置的引用指向链表的下一个即可
             */
            else if (node == p)
                tab[index] = node.next;
            /**
             * 如果找到的本来就是链表上的节点,也简单,将待删除节点的上一个节点的next指向待删除节点的
             * next,隔离开待删除节点即可
             */
            else
                p.next = node.next;
            ++modCount;
            --size;
            //删除后可能存在存储结构的调整,可参考【LinkedHashMap如何保证顺序性】中remove方法
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}
复制代码

removeTreeNodeメソッドの特定の実装は、TreeMapの原則の実装と一般的なメソッドを参照できます。

afterNodeRemovalメソッドの特定の実装は、LinkedHashMapの詳細な分析を参照できますが、ここではHashMapの空のメソッドを使用しています。これは実際には意味がありません。

3.トラバース

順次問題

コレクションとして、HashSetには、通常のforループ、拡張forループ、イテレーターなど、さまざまなトラバーサルメソッドがあります。イテレータートラバーサルを見てみましょう。

public static void main(String[] args) {
    HashSet<String> setString = new HashSet<> ();
    setString.add("星期一");
    setString.add("星期二");
    setString.add("星期三");
    setString.add("星期四");
    setString.add("星期五");

    Iterator it = setString.iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
}
复制代码

印刷結果は何ですか?

星期二
星期三
星期四
星期五
星期一
复制代码

予想どおり、HashSetはHashMapを介して実装されます。HashMapはhash(key)を使用して保存場所を決定します。保存順序がないため、HashSetが通過する要素は挿入順ではありません。

高速障害の問題

以前の他のコレクションでこのデモンストレーションをすでに行っていますが、この問題を強調するために、ここで別のデモンストレーションを行います。もちろん、使用シナリオは、トラバーサルプロセス。

@Test
public void iterator() {
    HashSet<String> setString = new HashSet<> ();
    setString.add("星期一");
    setString.add("星期二");
    setString.add("星期三");
    setString.add("星期四");
    setString.add("星期五");
    System.out.println(setString.size());
    Iterator<String> it = setString.iterator();
    while (it.hasNext()) {
        String tmp=it.next();
        if (tmp.equals("星期三")){
             setString.remove(tmp);
        }
        System.out.println(tmp);
    }
    System.out.println(setString.size());
}
复制代码

運転結果

5
星期二
星期三
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.HashMap$HashIterator.nextNode(HashMap.java:1445)
	at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
	at datastructure.java数据类型.hash.JavaHashSet.main(JavaHashSet.java:17)
复制代码

少し変更するだけです

@Test
public void iterator() {
    HashSet<String> setString = new HashSet<> ();
    setString.add("星期一");
    setString.add("星期二");
    setString.add("星期三");
    setString.add("星期四");
    setString.add("星期五");
    System.out.println(setString.size());
    Iterator<String> it = setString.iterator();
    while (it.hasNext()) {
        String tmp=it.next();
        if (tmp.equals("星期三")){
            it.remove();
        }
        System.out.println(tmp);
    }
    System.out.println(setString.size());
}
复制代码
5
星期二
星期三
星期四
星期五
星期一
4
复制代码

3.まとめ

HashSetは、実際には特定のシナリオで触媒されるデータ構造です。独自の実装はほとんどありません。すべての関数はHashMapを使用して実現されます。この記事では、HashSetaddメソッドについてもいくつか質問します。判断しないでください。最初に存在しますが、HashMap putメソッドに直接移動し、putの戻り値に従って結果を判断します。

HashSetのパフォーマンス

反復では実際のストレージ要素の数と容量のサイズを考慮する必要があるため、容量はHashSetの反復パフォーマンスに影響を与えることに注意してください。

 

Javaデータ型シリーズのHashSet

 

おすすめ

転載: blog.csdn.net/a159357445566/article/details/115210866