1. 程式人生 > >HashSet資料結構介紹

HashSet資料結構介紹

hashSet無參建構函式

   //hashset的預設建構函式,實際是創造一個hashmap物件
     public HashSet() {
         map = new HashMap<>();
      }

因為hashmap的擴充套件因子是0.75,及當0.75時就自動擴充套件,用構造的函式集合大小去初始 化hashmap,用擴 展集合的大小除以0.75+1與16比較,取較大的值作為初始化hashmap集合 的大小

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

hashset通過固定集合大小初始化

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

hashSet新增集合元素

//hashSet新增集合元素也是通過hashMap新增的集合元素,如果集合存在該元素,則返回false,不存在則返回true
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

hashSet刪除元素

//通過hashmap的刪除方法刪除集合元素, 刪除成功返回true,失敗false
public boolean remove(Object o) {
    return map.remove(o)==PRESENT;
}

HashSet清空集合元素

//hashSet清空集合元素,是通過hashmap的clear清楚方法清空集合的,
public void clear() {
    map.clear();
}