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 asMAXIMUM_CAPACITY). If we hit this limit, we stop resizing entirely (handled in the priorifblock).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^30and16 >=16), sonewThr = 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=12becomesnewThr.
内容的提问来源于stack exchange,提问作者xingbin
相关产品推荐
相关产品推荐

