详述HashSet类add方法(一)

首先,同一个对象调用多次该方法,结果相同;不同对象,如果重写hashCode方法,使得其返回值相同,则多次调用该方法,结果相同。

import 集合3.Student;

public class Test {

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

	public static void main(String[] args) {
		System.out.println(hash(null));

		Integer a = 11;
		Integer b = new Integer(11);
		System.out.println(hash(a));
		System.out.println(hash(b));

		String str1 = "11111";
		String str2 = new String("11111");
		System.out.println(hash(str1));
		System.out.println(hash(str2));

		// 同一个对象调用多次该方法,结果相同;不同对象,如果重写了hashCode方法,使得其返回值相同,则多次调用该方法,结果相同;
		Student stu1 = new Student();
		Student stu2 = new Student();
		System.out.println(hash(stu1));
		System.out.println(hash(stu2));
	}
}
//输出结果:
//0
//11
//11
//46760248
//46760248
//5433712
//2430314

那么如果我在Studet类里重写HashCode方法,使其返回值始终为1,那么在h = key.hashCode()中值一样,那么最后的结果也会一样:

public class Student {

	@Override
	public int hashCode() {
		return 1;
	}
}
//上面代码输出结果将会变为:
//0
//11
//11
//46760248
//46760248
//1
//1

我们对他的源代码进行分析:

import java.util.HashSet;

public class Test2 {

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

HashSet add方法:

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

HashMap put方法

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

HashMap putVal方法

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为全局变量table赋值
	if ((tab = table) == null || (n = tab.length) == 0)//table为null,tab为null,则(tab = table) == null为true
		n = (tab = resize()).length;//resize()方法直接为table返回newTab,resize方法也返回newTab,所以,table与tab是一个对象,数组长度16
	if ((p = tab[i = (n - 1) & hash]) == null)// i = (n - 1) & hash 数组长度-1  & hash值,i是下表  tab[i = (n - 1) & hash],因为目前只存储一个值,所以一定为null
		tab[i] = newNode(hash, key, value, null);// tab[i] I   (n - 1) & hash 为(n - 1) & hash添加一个元素,因为数组为地址传递,所以table全部变量i也有值
	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;
}

resize方法:
这里可以看出,resize()方法直接为table返回newTab,resize方法也返回newTab,所以,table与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];
	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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值