Jdk7不同集合的扩容机制

Jdk7不同集合的扩容机制

集合类初始容量负载因子扩容公式扩容时机
ArrayList10新容量 = 旧容量 × 1.5元素数量超过容量时
HashMap160.75新容量 = 旧容量 × 2元素数量超过 容量 × 负载因子
HashSet160.75新容量 = 旧容量 × 2元素数量超过 容量 × 负载因子
Vector10新容量 = 旧容量 + 增量 或 × 2元素数量超过容量时
Hashtable110.75新容量 = 旧容量 × 2 + 1元素数量超过 容量 × 负载因子

通过了解不同集合类的扩容机制,可以更好地选择和使用合适的集合类,避免频繁扩容带来的性能开销。

ArrayList

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    // newCapacity = oldCapacity + oldCapacity / 2
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

HashMap

头插法

void addEntry(int hash, K key, V value, int bucketIndex) {
    if ((size >= threshold) && (null != table[bucketIndex])) {
        // 旧容量 * 2
        resize(2 * table.length);
        hash = (null != key) ? hash(key) : 0;
        bucketIndex = indexFor(hash, table.length);
    }

    createEntry(hash, key, value, bucketIndex);
}

HashSet

通过HashMap实现的.

public HashSet() {
        map = new HashMap<>();
    }

Hashtable

protected void rehash() {
    HashtableEntry e, old;
    int i, index;
    int oldCapacity = table.length;
    HashtableEntry oldTable[] = table;
	// 新容量 = 旧容量 × 2 + 1
    int newCapacity = oldCapacity * 2 + 1;
    HashtableEntry newTable[] = new HashtableEntry[newCapacity];

    threshold = (int)(newCapacity * loadFactor);
    table = newTable;

    for (i = oldCapacity ; i-- > 0 ;) {
        for (old = oldTable[i] ; old != null ; ) {
            e = old;
            old = old.next;
            index = (e.hash & 0x7FFFFFFF) % newCapacity;
            e.next = newTable[index];
            newTable[index] = e;
        }
    }
}

Vector

private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半山猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值