HashSet中add()方法执行过程的分析

		HashSet<String> set = new HashSet<>();
		set.add("Tom");
		set.add("Tom");
		set.add("Lucy");

执行步骤

  1. HashSet的构造方法
    public HashSet() {
    	//创建了一个HashMap对象
        map = new HashMap<>();
    }

  1. HashSet的add方法源码
    public boolean add(E e) {
    // 调用了map中的put的方法
    //HashSet存储的数据实质存在了HashMap的key
        return map.put(e, PRESENT)==null;
    }
  1. HashMap中的put(K key, V value)方法
 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
  1. HashMap中的hash(Object key)方法
static final int hash(Object key) {
        int h;
        //如果出入的对象不为空则调用传入对象的hashCode()方法,返回计算的结果
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
  1. 调用HashMap中的
    putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict)方法

    执行第一个 set.add(“Tom”) 的时候分析
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
//		1.table为HashMap中的成员变量,到目前为止已经执行的普通方法未给table赋值,
//		  查看HashMap的构造方法,也未给table赋值的语句,所以这里的table为null。
//		  又因为是逻辑或运算有短路效果所以只判断前半句为真就执行下面的语句
        if ((tab = table) == null || (n = tab.length) == 0)
//			2.这里的resize()返回的值为默认的长度为16,并把resize()赋给tab
//			resize()和tab指向的同一个对象,主要原因后面分析
//			而table和resize()都赋值给tab.所以他们三个指向同一对象
            n = (tab = resize()).length;
//		3.这里通过把表达式((n - 1) & hash)结果赋给i,可以找tab[i]的值
//		判断tab[i]是否为null,如果为空就把"Tom"对象存进去.
//		同样的table作为全局变量指向的对象,就把"Tom"对象存入了
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                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);
                        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;
            }
        }
//		4.接上面的因为上面已经执行了if的语句所以不执行else部分
//		所以代码从这里开始执行,返回null
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

为什么resize()和tab指向的同一个对象?

 final Node<K,V>[] resize() {

        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        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)
                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"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
//		(1).newTab赋值给全局遍历table,所以table指向newTabl指向的对象
        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;
                        }
                    }
                }
            }
        }
//		(2).上面并没有return语句,所以下面的return一定执行
//		所以resize()返回值也是newTab指向的对象,
//		那么table和resize()指向的就是同一个对象
        return newTab;
    )

  1. 继续执行下一行 set.add(“Tom”)语句的时候同样再次执行HashMap中的putValue()方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
//		接上一个putVal()方法
//		5.这里因为table不为空所以不执行if语句里面的内容        
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
//		6.table长度不变所以n是16,
//		而第一个"Tom"和第二个"Tom"的hash值一样,tab[i]把值赋给p
//		所以这里得到的i和第一个"Tom"的i相同,tab[i]里面不为null
//		这里不执行if语句里面的内容,所以并没有把第二个"Tom"存入
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
//		执行else语句内容
        else {
            Node<K,V> e; K k;
//          7.这里的p.hash为传入第一个"Tom"的hash,
//			后面是第二个"Tom"的hash他们两个hash值相同 返回true
//			而第一个"Tom"的地址值和第二个"Tom"的地址值相同所以&&运算符后面的也为true
//			所以这里把第一个"Tom"(tab[i])的地址值赋给e
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                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);
                        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;
                }
            }
//			8.因为e不为空所以执行if语句的内容,返回第一个"Tom"的值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

所以这里第二个"Tom"并没有存入到set中

这里对hash方法进行解释

	static int hash(Object key) {
		int h;
		return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
	}
		int hash = 0;
//		String类型:内容相同,返回值相同,
//		调用了String类型里面的hashCode()方法,多态
		hash = hash("Jim");
		System.out.println(hash);
		hash = hash(new String("Jim"));
		System.out.println(hash);
		
//		基本数据类型的包装类:内容相同,返回值相同,
//		调用了基本数据类型包装类的hashCode()方法,多态
		hash = hash(1000);
		System.out.println(hash);
		hash = hash(new Integer(1000));
		System.out.println(hash);
		
//		自定义类型:如果地址不同则返回值也不同,
//		调用了Object类中的hashCode()方法,不是多态因为没有重写
//		因为这里是两个对象所以他们返回的方法也一样
		hash = hash(new Student());
		System.out.println(hash);
		hash = hash(new Student());
		System.out.println(hash);
	}
}

class Student{
	
}

结果:

74479
74479
1000
1000
2018677104
1311071082
  1. 当执行执行set.add(“Lucy”)将会再次执行HashMap中的putValue()方法
 final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
 //		接第二次添加"Tom"字符串
 //		9. table不为空并把值赋给tab,而且tab的长度为16赋给n,长度不等于0
 //		所以if语句中的代码不执行
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
//		10.这里的n为16,但是因为"Tom"和"Lucy"的hash值并不相同那么i也不同
//		所以tab[i]里面为null,并把"Lucy"对象存到tab[i]中,不执行else语句的内容
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                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);
                        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;
            }
        }
//		继续执行程序,返回null
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

从HashSet源码可以看出,

  1. HashSet存储元素靠HashMap实现的(存入到HashMap的key中),
  2. 通过分析HashMap中的putVal()方法可以看出HashSet不能存储相同的元素。

猜你喜欢

转载自blog.csdn.net/qq_35302939/article/details/89681371
今日推荐