hashSet方法源码解析

HashSet特点:

无序
唯一
只能有一个null值

主要考虑因素

* 1.HashSet是如何保证元素唯一的?

hashCode equals
其实原本只要比较元素对象的内容即可,但是:直接比较内容效率低,因为内容会有多项,所以引出了比较hash值的方法。
浅谈hash值的由来:是object的属性 每个对象有,每个对象生成的hashcode也不一样,重写hashcode方法后,由于方法中的返回值与元素内容紧密相关,就可以保证同样的内容产生的hash值相同-》相同的对象hashcode一致

* 2.HashSet是如何导致元素无序?

元素存储到哈希表结构当中是通过 对象的hashCode经过某种运算产生的相对不确定的数

* 3.HashSet为什么和存储不一样,却每次遍历的顺序都一样?

因为每次遍历的时候是同一个对象,同一个对象产生的哈希值是一样的

结论:

1.哈希值的结果和存储的对象本身有关
2.哈希值的结果和存储的对象的hashCode有关
3.哈希值同时是通过异或和移位产生的一个整数值,这个值是没有规律,但是每次运算的结果是一样
4.哈希算法返回的哈希值是一个整数,这个整数作为索引存储在哈希表结构当中
5.判断两个元素是否重复比较 hashCode 还有 equals 方法

在这里插入图片描述
在这里插入图片描述

HashSet<String> hs = new HashSet<>();
hs.add("ab");

HashSet类中部分源码:

class HashSet {
	private transient HashMap<E,Object> map;
	private static final Object PRESENT = new Object(); 0x0001

	public HashSet() {
        map = new HashMap<>();  //实际上内部是hashmap
    }
    					"ab"
    public boolean add(E e) {
    				"ab"
        return map.put(e, 0x0001)==null;
    }
}

hashset()

先观察hashset()—>实质就是新建hashmap对象
进入HashMap类中:

class HashMap {
	static final float DEFAULT_LOAD_FACTOR = 0.75f;
	public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
   //loadFactor:加载因子----------------------------------------
    public V put(K key, V value) {
    	// 				hash("ab")	"ab"	
        return putVal(hash(key), key, value, false, true);
    }
	1.哈希值的结果和存储的对象本身有关
    2.哈希值的结果和存储的对象的hashCode有关
    3.哈希值同时是通过异或和移位产生的一个整数值,这个值是没有规律,但是每次运算的结果是一样
    4.哈希算法返回的哈希值是一个整数,这个整数作为索引存储在哈希表结构当中
    5.判断两个元素是否重复比较 hashCode 还有 equals 方法
     					   "ab"
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    					32457 "ab"   0x0001
    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;
                }
       //----------------------------------max--------------------------------------
       当hash值相等并且值相等才判断两个obj相同
            }
            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;
    }
}
    

关于HashSet中的add

//属于HashSet类中
public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
private static final Object PRESENT = new Object(); 0x0001

PRESENT:指向Object对象的地址
进入map.put中:(在HashMap中)

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    

进入putVal()

				hash("ab")   "ab"   PRESENT( 0x0001)
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;
    }

hashmap中:表示hash的值和传过来的key相关

 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值