9.为什么hashtable的扩容是2倍+1

  9.为什么hashtable的扩容是2倍+1    

protected void rehash() {  
        int oldCapacity = table.length;//旧容量  
        Entry[] oldMap = table;//旧的桶数组  
        // overflow-conscious code  
        int newCapacity = (oldCapacity << 1) + 1;//新容量为老容量的2倍加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);  
        boolean currentAltHashing = useAltHashing;  
        useAltHashing = sun.misc.VM.isBooted() &&  
                (newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);  
        boolean rehash = currentAltHashing ^ useAltHashing;  
        table = newMap;  
        for (int i = oldCapacity ; i-- > 0 ;) {//转移键值对到新数组  
            for (Entry old = oldMap[i] ; old != null ; ) {  
                Entry e = old;  
                old = old.next;  
                if (rehash) {  
                    e.hash = hash(e.key);  
                }  
                int index = (e.hash & 0x7FFFFFFF) % newCapacity;  
                e.next = newMap[index];  
                newMap[index] = e;  
            }  
        }  
    } 

 

你可能感兴趣的:(java面试题整理)