简述HashSet的add方法


简述HashSet的add方法

HashSet的add方法源码

//返回布尔值 如果是null返回true,否则返回false
public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
//传入 key value 返回一个value值
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
// 传入 调用key的hash方法的值、key、value、false、true
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)//判断tab是否为空,长度是否等于0
        (1)  n = (tab = resize()).length;//将tab初始化,长度为16,n=16
        if ((p = tab[i = (n - 1) & hash]) == null)//第二次添加hash值相同的对象时p不为null为第一次添加的node对象
            tab[i] = newNode(hash, key, value, null);//第一次添加p==null添加成功!
        else {//添加不成功走else
            Node<K,V> e; K k;//局部变量
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //如果第一次添加的hash值本次添加的hash值相同时&&(地址相同||(本次key不为null&&调本次key的equals函数)
                e = p;//条件成立 将第一次添加的p对象赋给局部Node对象e
            else if (p instanceof TreeNode)//判断是否为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节点为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;
                }
            }
            //判断e是否为null e不为null则为重复
            if (e != null) { // existing mapping for key
                //此处e是第一次添加的p,将e的value赋值给oldvalue
                V oldValue = e.value;
                //onlyIfAbsent为false,!onlyIfAbsent为true
                if (!onlyIfAbsent || oldValue == null)
                   	//将第二次的value赋值给e的value
                    e.value = value;
                afterNodeAccess(e);
               	//返回oldvalue即第一次的value
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

(一)String 类型

HashSet<String> set = new HashSet<String>();
		set.add("123");//第一次添加直接添加走(1)
		System.out.println(set.add("123"));//输出结果为false
//第二次添加时tab不为null,p不为null走else,string"123"hashcode相同hash也一样,地址也一样,不为空,equals也相同。故输出结果为false

(二)Integer类型

HashSet<Integer> in = new HashSet<Integer>();
		in.add(12);
		System.out.println(in.add(12));//输出结果为false
//同string类型,Integer类型的hashcode就是本身

(三)自定义类型

//比如我们定义一个自定义类型Student类,要求Id相同即认为是一个对象,Id不能重复
HashSet<Student> stu = new HashSet<Student>();
//创建一个Id为123的Student对象s
		Student s = new Student("123");
//第一次添加Student类型的s对象
		stu.add(s);
//第二次添加时走else,由于两个对象的hashcode不一样(不重写hashcode方法返回的是地址),并且地址不同,equals比较地址也不相同,故可以存进去结果为true
		System.out.println(stu.add(new Student("123")));//输出结果为true
//如果想要通过Id实现去重,需要重写equals和hashCode方法。这时添加Id一样的对象时,调用子类的hashCode的方法,hash值相同,地址不同,调用equals方法判断也相同。则if判断成立,将p赋给e,e不为null实现去重。
@Override
public boolean equals(Object obj) {
	if (obj instanceof Student) {
		Student s = (Student) obj;
		return this.id.equals(s.id);
	}
	return false;
}
@Override
public int hashCode() {
	return id.hashCode();
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM