Java_HashSet工作原理

This class implements the Set interface, backed by a hash table (actually a HashMap 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 null element.

HashSet實現了Set接口,其本質是一個HashMap,只使用到了HashMap的key值,value是一個固定的值。對HashSet進行迭代的時候,不能保證其迭代的順序,其允許添空值。

簡單例子如下:

@SuppressWarnings(value = { "all" })
public class TestHashSet {
    public static void main(String[] args) {
        Set set=new HashSet();
        set.add("數學");
        set.add("化學");
        set.add("物理");
        set.add("生物");
        set.add("政治");
    }
}

這裏寫圖片描述


HashSet部分源碼:

//底層用於用一個HashMap對值進行存放
private transient HashMap<E,Object> map;
//對HashMap的value統一的設置爲相同的一個object
private static final Object PRESENT = new Object();
//這裏可以看出創建HashSet的時候,實際上是創建了一個HashMap
//其容量大小爲16,負載因子爲0.75
public HashSet() {
        map = new HashMap<>();
    }
......
 //迭代的時候,都是調用相應map的方法
 public Iterator<E> iterator() {
        return map.keySet().iterator();
    }
public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

總結:
HashSet的本質是一個HashMap,只是其value是一個固定的,相同的object,其它操作都是操作相應的HashMap的方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章