You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HashMap#resize方法细节解析:newThr两种计算方式的疑问

What's the Meaning of the First Condition?

Let's break down the condition step by step:

else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY)
  • newCap = oldCap << 1: First, we compute the new capacity by doubling the old one (bitwise left shift is faster than multiplying by 2).
  • newCap < MAXIMUM_CAPACITY: Ensures we don't exceed HashMap's hard maximum capacity (2^30, defined as MAXIMUM_CAPACITY). If we hit this limit, we stop resizing entirely (handled in the prior if block).
  • oldCap >= DEFAULT_INITIAL_CAPACITY: Confirms the map has moved past its initial bootstrap phase. The default initial capacity is 16—this means we only use the optimized threshold doubling once the map has grown to at least that size.

In short, this condition says: "We can safely use the fast threshold doubling only when the map is large enough to be past its initial setup, and doubling the capacity won't push us over the maximum limit."


Quick Example to Clarify

  • Default settings scenario:

    • oldCap = 16, oldThr = 12 (16 * 0.75)
    • Resize triggers, newCap = 32
    • The first condition is satisfied (32 < 2^30 and 16 >=16), so newThr = 12 <<1 =24
    • This matches the result of 32 *0.75=24, but is computed faster with a bit shift.
  • Custom small initial capacity scenario:

    • oldCap=8, oldThr=6 (8*0.75)
    • Resize triggers, newCap=16
    • The first condition fails (8 <16), so we fall back to the second method: 16*0.75=12 becomes newThr.

内容的提问来源于stack exchange,提问作者xingbin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:07:26