- //Hashtable 默认构造函数
- public Hashtable() {
- this(11, 0.75f);
- }
- //Hashtable 扩容
- protected void rehash() {
- int oldCapacity = table.length;
- Entry < ?,
- ?>[] oldMap = table;
- // overflow-conscious code
- // 位运算相当于 2n+1
- int newCapacity = (oldCapacity << 1) + 1;
- if (newCapacity - MAX_ARRAY_SIZE > 0) {
- if (oldCapacity == MAX_ARRAY_SIZE)
- // Keep running with MAX_ARRAY_SIZE buckets
- return;
- newCapacity = MAX_ARRAY_SIZE;
- }
- Entry < ?,
- ?>[] newMap = new Entry < ?,
- ?>[newCapacity];
- modCount++;
- threshold = (int) Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
- table = newMap;
- for (int i = oldCapacity; i-->0;) {
- for (Entry < K, V > old = (Entry < K, V > ) oldMap[i]; old != null;) {
- Entry < K,
- V > e = old;
- old = old.next;
- int index = (e.hash & 0x7FFFFFFF) % newCapacity;
- e.next = (Entry < K, V > ) newMap[index];
- newMap[index] = e;
- }
- }
- }
- //HashMap 扩容
- 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;
- }
- // 新容量调整旧容量的 2 倍
- 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;
- // 初始化默认为 16
- else { // zero initial threshold signifies using defaults
- newCap = DEFAULT_INITIAL_CAPACITY;
- newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
- }
- // 计算新的 resize 上限
- 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;
- }
来源: https://www.cnblogs.com/wtzbk/p/8591559.html