今天寫(xiě)了一下 Activity的管理類 在移除內(nèi)部Stack與Activity的關(guān)聯(lián)時(shí) 本來(lái)寫(xiě)的時(shí)候 是直接移除傳入的Activity
然后看了一下 EventBus 的代碼 發(fā)現(xiàn) EventBus 在取消注冊(cè)的時(shí)候 內(nèi)部是通過(guò)如下代碼 實(shí)現(xiàn)的
/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
然后看下 集合類的內(nèi)部 實(shí)現(xiàn) remove對(duì)象方法
public synchronized boolean removeElement(Object obj) {
modCount++;
int i = indexOf(obj);
if (i >= 0) {
removeElementAt(i);
return true;
}
return false;
}
在indexOf中 遍歷獲取到傳入對(duì)象的角標(biāo)
public synchronized int indexOf(Object o, int index) {
if (o == null) {
for (int i = index ; i < elementCount ; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = index ; i < elementCount ; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
經(jīng)過(guò)一番調(diào)用 也是還最后通過(guò)遍歷獲取到 傳入對(duì)象的角標(biāo) 來(lái)移除的 既然都會(huì)遍歷的話 我們不如在外部遍歷 用類似的EventBus 的寫(xiě)法 在移除的同時(shí) 將集合和角標(biāo)減一 這樣還可以 避免在遍歷中移除對(duì)象 有可能導(dǎo)致的空指針等問(wèn)題