Java中详述HashSet类add方法(一)

对象名.add方法添加元素,元素不重复

import java.util.HashSet;

public class Test2 {

	public static void main(String[] args) {
		
		HashSet<String> names = new HashSet<String>();//调用构造方法时,创建HashMap集合对象
	    System.out.println(names.add("957"));//向HashMap集合的key存值,HashMap value是一个常量 Object	    
	}

对.add()方法进行分析:
源代码:

	public boolean add(E e) {//E e为输入的"wjq"
        return map.put(e, PRESENT)==null;
	}

之后需要进行map.put(e, PRESENT)==null; 方法,对.put()方法进行源代码分析:

	public V put(K key, V value) {//此时K key为"wjq",V value为常量PRESENT
        return putVal(hash(key), key, value, false, true);
    }

代码需要进行putVal(hash(key), key, value, false, true); 方法,对putVal()方法源代码及部分语句定义时的代码进行分析:

	static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

	transient Node<K,V>[] table;//table=null

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        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;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

此时,Node<K,V>[] tab; 方法中首先定义数组变量变量 tab。

		if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

这是对tab进行赋值,tab=table=null,判断为true进行对n赋值的操作,需要对resize方法代码进行分析:

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];
        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;
    }

首先,将table的值赋给oldTab变量=null,在下面进行oldCap的三目运算,返回值为0;之后进行

		else {               
		// zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
		        }

对newCap赋值为DEFAULT_INITIAL_CAPACITY;(默认值16)随后关注这一段代码:

		threshold = newThr;
		        @SuppressWarnings({"rawtypes","unchecked"})
		            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
		table = newTab;
		if (oldTab != null) {
		……
		}
		return newTable;

由于oldTable=null,不满足 if (oldTab != null) 条件,因此直接进行return newTable的操作,返回newTable,此时全局变量table=newTable,其数组长度为16,对tab赋值为table后统计其长度,统计长度n=16;随后进行后续操作:

		if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

在计算下标i时,i = (n - 1) & hash=数组长度-1 & hash,由于目前数组只存储一个值[待存值(“wjq”)],因此必定为null。进行对tab[i]的赋值操作,将newNode的元素赋给tab[i],最终返回null进入上一级put方法,从而put方法的返回值为null,此时:

	public boolean add(E e) {//E e为输入的"wjq"
        return map.put(e, PRESENT)==null;
	}

return map.put(e, PRESENT)==null; 成立,结果为true,因此,返回值为true。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值