HashSet 源码分析

HashSet 源码分析

Set类似于一个罐子,程序可以依次把多个对象“丢进”Set集合,而Set集合通常不能记住元素的添加顺序。

实际上Set就是Collection只是行为略有不同(Set不允许包含重复元素)。

Set 和和 List 接口一样, Set 接口也是 Collection 的子接口,因此,常用方法和 Collection 接口一样。

image-20220403211053174

HashSet是Set接口的典型实现,大多数时候使用Set集合时就是使用这个实现类。HashSet按Hash算法来存储集合中的元素,因此具有很好的存取和查找性能。

底层数据结构是**哈希表 = 数组+链表 **。

image-20220403222450188

源码分析

示例:

Set set = new HashSet();

set.add("Ale");
set.add("Boy");
set.add("Ciry");

System.out.println(set);

初始化

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable{	
	    // 调用构造函数
        public HashSet() {
                map = new HashMap<>();
            }
        ......    
	}
	// 构造一个具有默认初始容量 (16) 和默认加载因子 (0.75) 的空 HashMap
	// DEFAULT_LOAD_FACTOR = 0.75
    public HashMap() {
    // all other fields defaulted
        this.loadFactor = DEFAULT_LOAD_FACTOR; 
    } 

image-20220403212714780

//HaspMap的说明
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    
    private static final long serialVersionUID = 362498820763181265L;
    
    //默认初始容量 - 必须是 2 的幂。JDK1.8中默认的初始容量是16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
   
   //规定负载因子为0.75。 容量负载超过 12 = 16*0.75 ,则需要扩容
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
    //单个数组中的链表长度超过8,则对链表进行树化。
    static final int TREEIFY_THRESHOLD = 8;
    
    //对其进行树化的的最小表容量。JDK规定为64,超过64这转化
     static final int MIN_TREEIFY_CAPACITY = 64;
    }

添加元素

/**
如果指定的元素尚不存在,则将其添加到此集合中。 
更正式地说,如果此集合不包含元素 e2,则将指定的元素 e 添加到此集合中,使得(e==null ? e2==null : e.equals(e2))。 
如果该集合已包含该元素,则调用将保持该集合不变并返回 false。

PRESENT在这里没有实用价值
**/
public boolean add(E e) {
	return map.put(e, PRESENT)==null;
}

public V put(K key, V value) {
	return putVal( hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
		//key表示当前需要添加的 元素
		
        Node<K,V>[] tab; 
        Node<K,V> p; //表示链表中的 头节点
        int n, i;
       
        if ((tab = table) == null || (n = tab.length) == 0)
        	// 若 表为null或 表长为0,对表 进行初始化或扩容
            n = (tab = resize()).length;
            
        //&为异或符号,两个相应位相同,结果为0,否则为1。
        //判断当前索引下数组中是否为空(是否含有有链表)
        if ((p = tab[i = (n - 1) & hash]) == null)
        	///若当前索引下为空,则将存放 该元素的节点作为 链表头
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; 
            K k;
            
         //比较头节点p的hash值 与需要添加元素key的hash值,若哈希值相同则不能将元素添加到链表尾
         //比较头节点的元素值是否等于key
         //若添加的元素为对象时,比较的是哈希值,这里产生一个问题(见特别注意),需要重写equals,否则就会造成可以添加相同的对象,与Set的性质冲突。
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                
                //这里e != null,会直接跳转到最后if (e != null) 
                e = p;
                //判断是否已经树化,已经树化,则将元素存放到树中
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            	//将当前元素放入节点中,并加入到表尾
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {	
                        p.next = newNode(hash, key, value, null);
                        
                        //若binCount >= 7,将链表进行树化
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    //
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //记录 HashSet的修改次数
        ++modCount;
        //判断是否需要扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
// 存放元素的节点
Node(int hash, K key, V value, Node<K,V> next) {
    this.hash = hash;
    this.key = key;
    this.value = value;
    this.next = next;
}

//哈希源码

static final int hash(Object key) {
	int h;
	return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

public int hashCode() {
	int h = hash;
	if (h == 0 && value.length > 0) {
	char val[] = value;
    for (int i = 0; i < value.length; i++) {
        h = 31 * h + val[i];
    }
	hash = h;
  }
	return h;
}

扩容源码

   //按照第一次扩容的
   final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        //记录当前表长 oldCap=16
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //需要扩容的负载容量大小 oldThr=12
        int oldThr = threshold;
        int newCap, newThr = 0;
        
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                //oldThr左移一位,newThr为 24 = 12*2
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        //创建新表,容量为32
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        
        //将旧表中的数据转移到扩容后的新表中
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

特别注意

若添加的元素为对象时,比较的是哈希值,这里产生一个问题(见特别注意),需要重写equals和hashCode,否则就会造成可以添加相同的对象,与Set的性质冲突。详细原理参考重写的源码

具体如下:

Set set = new HashSet();

//String中已经重写过equals和hashCode
set.add(new String("a"));
set.add(new String("a"));

//因为没有重写,所有会产生两个Cat
set.add(new Animal("Cat"));
set.add(new Animal("Cat"));

System.out.println(set);

//没有重写equals和hashCode的自定义类
class  Animal{
    String name;

    public Animal(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
    
}

运行结果如下:
image-20220404001427180
重写后的代码:

class  Animal{
    String name;

    public Animal(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return  name ;
    }
    
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Animal animal = (Animal) o;
        return Objects.equals(name, animal.name);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}

image-20220404002735802

移除元素

    //函数在HashSet中
    public boolean remove(Object o) {
        return map.remove(o)==PRESENT;
    }
     
     //函数在HashMap中
    public V remove(Object key) {
    	Node<K,V> e;
    	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;
        //判断表中是否有所要删除的元素
        //直接根据哈希值索引到元素p = tab[index = (n - 1) & hash]
        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;
            
            //比较 哈希值等 条件是否满足
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //将表中所要删除的元素赋予node
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    //while循环遍历到链表尾节点
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||(value != null && value.equals(v)))){
                // 判断是否已经树化,若树化则在树中删除
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                	//直接将node的下一个节点存入
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值