這些函數(shù)都相對簡單。因?yàn)榇鎯Φ脑乜赡転閚ull,所以判斷的時(shí)候多了一次。
public int size() { return size;}public boolean isEmpty() { return size == 0;}public boolean contains(Object o) { return indexOf(o) >= 0;}public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1;}public int lastIndexOf(Object o) { if (o == null) { for (int i = size-1; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = size-1; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1;}關(guān)于batchRemove()方法 1. 批量刪除的方法,具體是對集合c和elementData的交集處理,這里詳細(xì)說明一下。
假如集合c和elementData的交集是U,那么,如果complement是true,elementData最終會只存儲U;如果complement是false,elementData最終刪除U。2. 在對elementData的元素進(jìn)行篩選的時(shí)候,這里使用了r、w兩個(gè)游標(biāo),從而避免從新開辟一個(gè)新的數(shù)組進(jìn)行存儲。這種方法也是比較常見的一種算法題。
private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { // 在原有數(shù)組上進(jìn)行篩選的方法,而不是另外開辟一個(gè)新的數(shù)組 for (; r < size; r++) if (c.contains(elementData[r]) == complement) elementData[w++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. if (r != size) { System.arraycopy(elementData, r, elementData, w, size - r); w += size - r; } if (w != size) { // clear to let GC do its work for (int i = w; i < size; i++) elementData[i] = null; modCount += size - w; size = w; modified = true; } } return modified;}
|
新聞熱點(diǎn)
疑難解答