編輯:關於 Android 程式設計
分析源碼之前,先了解 ArrayMap 的儲存結構——它和 HashMap、SparseArray 的思路完全不同。
Java 提供了 HashMap,但對行動裝置而言,HashMap 對空間的利用太「浪費」:每個 entry 都是一個物件,還有鏈結節點與裝箱開銷。所以 Android 提供了 SparseArray 與 ArrayMap。兩者都基於二分查找,資料量大時最壞情況會比 HashMap 慢很多,因此官方建議資料量在千以內使用。
SparseArray 的 key 只能是 int,不會做裝箱操作。它用兩個陣列:一個存 key,一個存 value。
查詢時用二分查找找出 key 對應的插入位置,所以 mKeys 必須保持有序。
值得注意的一點:remove() 不會立刻清理資料,而是把該位置標記為一個名為 DELETE 的哨兵物件;等到必要的環節(例如後續的 put 或 get)才呼叫 gc 統一清理這些標記空間。這樣可以合併多次刪除的搬移成本。
ArrayMap 的設計比 SparseArray 更精緻,先從它的四個成員陣列說起:
mHashes:保存每個 key 對應的 hashCode。mArray:保存鍵值對,結構是 [key1, value1, key2, value2, key3, value3, ...],長度為 mSize 的兩倍。mBaseCache:物件池。當資料量從 4 成長到 8 時,這裡會保存原本用過的 mHashes 與 mArray;若之後資料量又降回 4,就能直接重用,不必重新配置記憶體。mTwiceBaseCache:與 mBaseCache 對應,觸發條件是資料量從 8 成長到 12。為什麼是「8 成長到 12」而不是 16?這是 ArrayMap 的一個優化點:它不是每次翻倍,而是用 mSize + (mSize >> 1),也就是每次增加二分之一。這樣能避免記憶體配置的劇烈跳動。
理解了這個結構,讀源碼就順暢多了。
int indexOf(Object key, int hash) {
final int N = mSize;
// 快速路徑:陣列為空,什麼都不用找
if (N == 0) {
return ~0;
}
// 二分查找 hashCode
int index = ContainerHelpers.binarySearch(mHashes, N, hash);
// 沒找到 hashCode,代表沒有這個 key,回傳負數
if (index < 0) {
return index;
}
// 該位置的 key 相同,就是要找的
if (key.equals(mArray[index << 1])) {
return index;
}
// 往 index 後方找:hashCode 相同但 key 不同的情況(hash 碰撞)
int end;
for (end = index + 1; end < N && mHashes[end] == hash; end++) {
if (key.equals(mArray[end << 1])) return end;
}
// 往 index 前方找
for (int i = index - 1; i >= 0 && mHashes[i] == hash; i--) {
if (key.equals(mArray[i << 1])) return i;
}
// 完全沒找到,回傳負數,其位元補數就是應該插入的位置。
// 這裡用 hash 鏈結的末端,能減少插入時需要搬移的陣列元素數量。
return ~end;
}
這段有兩個精妙之處。第一,index << 1 就是 index × 2,因為 mArray 是 key/value 交錯排列,第 index 個 key 的位置必然是 index×2。第二,回傳「~index」(位元 NOT)而不是單純的 -1,這樣呼叫端可以用 ~index 直接得到插入點,省下一次查找。
至於為什麼要往前後都找:因為不同的 key 可能有相同的 hashCode(碰撞)。二分查找只能保證找到「某個」hash 相符的位置,真正要確認 key 相等,還得沿著 hash 相同的區間線性掃一遍。
public V put(K key, V value) {
final int hash;
int index;
// key 為 null 時走 indexOfNull,否則走 indexOf
if (key == null) {
hash = 0;
index = indexOfNull();
} else {
hash = key.hashCode();
index = indexOf(key, hash);
}
// index >= 0 代表之前 put 過相同的 key,直接替換 value 並回傳舊值。
// 注意 mArray 同時存了 key 與 value,所以 value 的位置是 index*2+1
if (index >= 0) {
index = (index << 1) + 1;
final V old = (V) mArray[index];
mArray[index] = value;
return old;
}
// 轉成正數,得到插入位置
index = ~index;
// 已存元素數等於 mHashes 長度,需要擴容
if (mSize >= mHashes.length) {
// 新容量:>=8 時增加 1/2;>=4 時翻倍;否則用 BASE_SIZE(4)
final int n = mSize >= (BASE_SIZE * 2) ? (mSize + (mSize >> 1))
: (mSize >= BASE_SIZE ? (BASE_SIZE * 2) : BASE_SIZE);
final int[] ohashes = mHashes;
final Object[] oarray = mArray;
allocArrays(n);
// 把舊資料搬到新陣列
if (mHashes.length > 0) {
System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length);
System.arraycopy(oarray, 0, mArray, 0, oarray.length);
}
// 舊陣列若容量為 4 或 8,放進物件池留著以後用;太大則直接丟棄
freeArrays(ohashes, oarray, mSize);
}
// 插入位置不在尾端,需要把後面的元素往後挪一格
if (index < mSize) {
System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index);
System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1);
}
mHashes[index] = hash;
mArray[index << 1] = key;
mArray[(index << 1) + 1] = value;
mSize++;
return null;
}
remove 在某些條件下會重新配置記憶體,讓 ArrayMap 占用的空間維持在合理區間,避免長期使用後記憶體越吃越多。但反過來說,這也代表 ArrayMap 是用「時間換空間」——而頻繁的配置與回收記憶體一定會耗時間。這個取捨是否划算,取決於你的使用情境。
/**
* 移除指定 index 的 key/value 對
* @return 該位置原本儲存的 value
*/
public V removeAt(int index) {
final Object old = mArray[(index << 1) + 1];
// 移除後就只剩 0 或 1 個元素,直接把兩個陣列清空歸還
if (mSize <= 1) {
freeArrays(mHashes, mArray, mSize);
mHashes = EmptyArray.INT;
mArray = EmptyArray.OBJECT;
mSize = 0;
} else {
// 原本配置的容量 > 8,但現在只用不到 1/3,則縮容
if (mHashes.length > (BASE_SIZE * 2) && mSize < mHashes.length / 3) {
// 不允許縮到 8 以下,避免在 4 與 8 之間反覆反覆配置(flapping)
final int n = mSize > (BASE_SIZE * 2)
? (mSize + (mSize >> 1)) : (BASE_SIZE * 2);
final int[] ohashes = mHashes;
final Object[] oarray = mArray;
allocArrays(n);
mSize--;
// 前半段直接複製
if (index > 0) {
System.arraycopy(ohashes, 0, mHashes, 0, index);
System.arraycopy(oarray, 0, mArray, 0, index << 1);
}
// 後半段往前補,兩段合起來就等於把 index 位置抽掉
if (index < mSize) {
System.arraycopy(ohashes, index + 1, mHashes, index, mSize - index);
System.arraycopy(oarray, (index + 1) << 1, mArray, index << 1, (mSize - index) << 1);
}
} else {
mSize--;
// 不縮容,直接把後面的元素往前挪
if (index < mSize) {
System.arraycopy(mHashes, index + 1, mHashes, index, mSize - index);
System.arraycopy(oarray, (index + 1) << 1, mArray, index << 1, (mSize - index) << 1);
}
// 挪完之後最後一格要清空,避免持有已移除物件的參考而無法回收
mArray[mSize << 1] = null;
mArray[(mSize << 1) + 1] = null;
}
}
return (V) old;
}
這裡的「1/3 門檻」與「不縮到 8 以下」是為了避免反覆配置:如果門檻設太寬鬆,使用者剛刪幾筆又新增幾筆,就會在兩個容量之間來回配置,效能反而更差。
private static void freeArrays(final int[] hashes, final Object[] array, final int size) {
// 容量為 8(BASE_SIZE*2)→ 放進 mTwiceBaseCache
if (hashes.length == (BASE_SIZE * 2)) {
synchronized (ArrayMap.class) {
if (mTwiceBaseCacheSize < CACHE_SIZE) {
// array[0] 指向舊的 mTwiceBaseCache,形成鏈結
array[0] = mTwiceBaseCache;
array[1] = hashes;
// 清掉 index 2 之後的元素,避免佔用記憶體
for (int i = (size << 1) - 1; i >= 2; i--) {
array[i] = null;
}
mTwiceBaseCache = array;
mTwiceBaseCacheSize++;
}
}
}
// 容量為 4(BASE_SIZE)→ 放進 mBaseCache
else if (hashes.length == BASE_SIZE) {
synchronized (ArrayMap.class) {
if (mBaseCacheSize < CACHE_SIZE) {
array[0] = mBaseCache;
array[1] = hashes;
for (int i = (size << 1) - 1; i >= 2; i--) {
array[i] = null;
}
mBaseCache = array;
mBaseCacheSize++;
}
}
}
}
這個設計很聰明:因為 mArray 的元素型別是 Object,所以它本身就能用來存「另一個陣列」。array[0] 存上一個被放回的 mArray、array[1] 存對應的 mHashes,就形成了一個小型鏈結串列,最多快取 CACHE_SIZE 份。這些快取是 static 的,所以整個 App 內所有 ArrayMap 實例共用同一個池子。
看懂 freeArrays 之後,allocArrays 就是反過來的動作。依請求容量分三支:
clear() 清空陣列並歸還記憶體,之後再新增元素需要重新配置空間;erase() 只清除陣列內容,空間仍保留著。若你預期之後還會塞入相近數量的資料,用 erase 比較划算。
主要邏輯都在 indexOf 裡了,get 剩下的事就是:呼叫 indexOf 找到位置,若為負數回傳 null,否則回傳 mArray[index << 1 | 1]。
把幾個常見的 Map 實現擺在一起比較:
一句話總結:小資料量、想省記憶體 → ArrayMap / SparseArray;大資料量、重視查詢速度 → HashMap。ArrayMap 用二分查找與物件池快取換取記憶體效率,是行動裝置上很典型的工程取捨。
以上就是 ArrayMap 源碼的解析,希望能幫助大家理解 Android 在容器實作上的設計思路。
Android 數據讀取與寫入(二):讓設定記住用戶的選擇
完成效果:選擇選項後退出,介面能記住用戶選擇的選項。 1. 利用 SharedPreferences 記住選擇的選項 主佈局:
Android Socket 通訊實作:用常駐 Service 打造長連線客戶端
Android 與伺服器通訊主要有兩條路:HTTP 與 Socket。兩者最大的差異在連線模型。 HTTP 走的是「請求—回應」:客戶端發請求才建立通道,伺服器回應後連線
Android 沉浸式狀態欄實戰:從原理到 API 21 完全透明
前言 這裡不打算爭論「沉浸式」這個詞用得準不準確,大家聽得懂就好。本文整理自實際專案中的經驗,歡迎一起探討。由於實習期間長期處於高強度加班狀態,一直沒時間做總結,直到某天
微信公眾號怎麼申請?免費註冊流程與三種類型的差別一次講清
從春節紅包開始,微信公眾號慢慢長成了我們生活的一部分:公益勸募、機票比價、 restaurants 優惠券、原創專欄,幾乎都能在訂閱列表裡找到。想把內容經營成一個公開的窗