以Android4.3的源码分析SparseArray的容量初始值到底是多少
//无参构造函数
public SparseArray() {
//这里无参构造函数调用有参构造函数
this(10);
}
紧接着
//有参构造函数
public SparseArray(int initialCapacity) {
//决定它初始容量的关键代码就是下边这行
initialCapacity = ArrayUtils.idealIntArraySize(initialCapacity);
mKeys = new int[initialCapacity];
mValues = new Object[initialCapacity];
mSize = 0;
}
紧接着看ArrayUtils.idealIntArraySize(initialCapacity);这里边到底做了什么
public class ArrayUtils{
private ArrayUtils() { /* cannot be instantiated */ }
//我写的注释已经很明确,这个for循环只有当1左移6位=64时
public static int idealByteArraySize(int need) {
//need= 40
for (int i = 4; i < 32; i++)
//if(40<=(1<<6=64)-12)成立
if (need <= (1 << i) - 12)
//1<<6=64-12=52 所以这里初始化的时候返回的值是52
return (1 << i) - 12;
return need;
}
public static int idealBooleanArraySize(int need) {
return idealByteArraySize(need);
}
public static int idealShortArraySize(int need) {
return idealByteArraySize(need * 2) / 2;
}
public static int idealCharArraySize(int need) {
return idealByteArraySize(need * 2) / 2;
}
//我们需要看的是这个方法,其他忽略
public static int idealIntArraySize(int need) {
//idealByteArraySize(10 * 4=40)=52/4=13写的已经够清楚了吧
return idealByteArraySize(need * 4) / 4;
}
public static int idealFloatArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealObjectArraySize(int need) {
return idealByteArraySize(need * 4) / 4;
}
public static int idealLongArraySize(int need) {
return idealByteArraySize(need * 8) / 8;
}
}