The SparseArrayCompat
class in the Android support library is a lightweight implementation of a map using arrays. Like many container implementations using arrays, it has a growing policy that ensures the array capacity is enough to hold all elements. In the SparseArrayCompat
implementation, the growing policy is expressed in ContainerHelpers.idealByteArraySize()
, which goes like this:
public static int idealByteArraySize(int need) {
for (int i = 4; i < 32; i++)
if (need <= (1 << i) - 12)
return (1 << i) - 12;
return need;
}
It appears to choose a closest power of 2 that is larger than or equal to the needed capacity. What I don't get is the subtraction of 12 in the return statement. The -12
term in the if
condition seems to be arbitrarily extra space wanted in case if the needed capacity grows in the near future, which makes sense, but the return statement gets rid of that extra space. Shouldn't the return statement just return (1 << i)
without the subtraction?
I would love to hear if anyone can help to explain this to me. I can't help but feel this tickle around my back without understanding why.
References:
Collection
implementations and also in most thread pools or similar things.