//指定位置索引 public E get(int index) { rangeCheck(index);
return elementData(index); } //直接索引第一个可以找到的对象 publicintindexOf(Object o) { if (o == null) { for (inti=0; i < size; i++) if (elementData[i]==null) return i; } else { for (inti=0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; }
删除
1 2 3 4 5 6 7 8 9 10
//直接清除 publicvoidclear() { modCount++; //大量的数据并且频繁操作可能引发频繁GC // clear to let GC do its work for (inti=0; i < size; i++) elementData[i] = null;
//AbstractList /* Overriding this method to take advantage of * the internals of the list implementation can <i>substantially</i> * improve the performance of the {@code clear} operation on this list * and its subLists. */ protectedvoidremoveRange(int fromIndex, int toIndex) { ListIterator<E> it = listIterator(fromIndex); for (int i=0, n=toIndex-fromIndex; i<n; i++) { it.next(); it.remove(); } }
//implementation improve the performance //为什么这个方法是protected 可以参考Effective Java一书中所述. //TODO 解释为什么 //这个方法是给subList用的 protectedvoidremoveRange(int fromIndex, int toIndex) { // Android-changed: Throw an IOOBE if toIndex < fromIndex as documented. // All the other cases (negative indices, or indices greater than the size // will be thrown by System#arrayCopy. if (toIndex < fromIndex) { thrownewIndexOutOfBoundsException("toIndex < fromIndex"); }
/** * Returns an iterator over the elements in this list in proper sequence. * * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>. * * @return an iterator over the elements in this list in proper sequence */ public Iterator<E> iterator() { //返回了Itr实例, 看ArrayList怎么实现的 returnnewItr(); }
/** * An optimized version of AbstractList.Itr 这里说的是一个优化过的AbstractList.Itr */ privateclassItrimplementsIterator<E> { // Android-changed: Add "limit" field to detect end of iteration. // The "limit" of this iterator. This is the size of the list at the time the // iterator was created. Adding & removing elements will invalidate the iteration // anyway (and cause next() to throw) so saving this value will guarantee that the // value of hasNext() remains stable and won't flap between true and false when elements // are added and removed from the list. protectedintlimit= ArrayList.this.size; // 迭代器的边界
int cursor; // index of next element to return intlastRet= -1; // index of last element returned; -1 if no such intexpectedModCount= modCount; //
publicbooleanhasNext() { return cursor < limit; }
@SuppressWarnings("unchecked") public E next() { if (modCount != expectedModCount) //如果修改和期望不符, 则抛出多线程修改异常. thrownewConcurrentModificationException(); inti= cursor; if (i >= limit) //边界检查 thrownewNoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownewConcurrentModificationException(); cursor = i + 1; //使用cursor增加1 return (E) elementData[lastRet = i]; }
publicvoidremove() { if (lastRet < 0) thrownewIllegalStateException(); if (modCount != expectedModCount) thrownewConcurrentModificationException();
@Override @SuppressWarnings("unchecked")//foreach的实现 publicvoidforEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); finalintsize= ArrayList.this.size; inti= cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { thrownewConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1;
if (modCount != expectedModCount) thrownewConcurrentModificationException(); } }
/** * An optimized version of AbstractList.ListItr 优化过的迭代器, 能够前后移动,是一个双向的迭代器,并且支持增删改查. */ privateclassListItrextendsItrimplementsListIterator<E> { ListItr(int index) { super(); cursor = index; }
funmain() { val mList = ArrayList<Int>(10) (1..10).forEach { i -> mList.add(i) } //modCount = 10 对list做了10次add操作 val itr = mList.iterator() // modCount = expectedModCount = 10
while (itr.hasNext()) { /** public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } //这里会检查modeCount != expectedModCount final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } */ val value = itr.next() // if (value == 5) mList.remove(value) //此时modeCount = 11 } } //或者使用foreach也可以, foreach的底层实现就是iterator
@SuppressWarnings("unchecked") public E previous() { checkForComodification(); inti= cursor - 1; if (i < 0) thrownewNoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) thrownewConcurrentModificationException(); cursor = i; return (E) elementData[offset + (lastRet = i)]; }
@SuppressWarnings("unchecked") publicvoidforEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); finalintsize= SubList.this.size; inti= cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (offset + i >= elementData.length) { thrownewConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[offset + (i++)]); } // update once at end of iteration to reduce heap write traffic lastRet = cursor = i; checkForComodification(); }
publicintnextIndex() { return cursor; }
publicintpreviousIndex() { return cursor - 1; }
publicvoidremove() { if (lastRet < 0) thrownewIllegalStateException(); checkForComodification();
publicinterfaceQueue<E> extendsCollection<E> { booleanadd(E e); booleanoffer(E e); E remove(); E poll(); //retrieves and remove the head of this queue E element();// retrieves the head but not remove, throw exception if queue is empty E peek();// retrieves the head but not remove. not throw exception. }
/** * Constructs an empty list. */ publicLinkedList() { }
/** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ publicLinkedList(Collection<? extends E> c) { this(); addAll(c); }
方法分析
增删改查
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/** * Links e as first element. */ privatevoidlinkFirst(E e) { final Node<E> f = first; final Node<E> newNode = newNode<>(null, e, f); first = newNode; if (f == null) last = newNode; else f.prev = newNode; size++; modCount++; }
/** * Links e as last element. */ voidlinkLast(E e) { final Node<E> l = last; final Node<E> newNode = newNode<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
1 2 3 4 5 6 7 8 9 10
/** * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #add}. * * @param e the element to add */ publicvoidaddLast(E e) { linkLast(e); }
增
1 2 3 4 5 6 7 8 9 10 11 12
/** * Appends the specified element to the end of this list. * * <p>This method is equivalent to {@link #addLast}. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ publicbooleanadd(E e) { linkLast(e); returntrue; }
publicbooleanaddAll(Collection<? extends E> c) { return addAll(size, c); }
publicbooleanaddAll(int index, Collection<? extends E> c) { //位置检查 checkPositionIndex(index); //将C转换为array Object[] a = c.toArray(); //a的长度 intnumNew= a.length; if (numNew == 0) returnfalse; //两个node Node<E> pred, succ; //如果刚好是到尾部, 将pred指向last if (index == size) { succ = null; pred = last; } else { //否则在指定的index处插入. succ = node(index); pred = succ.prev; } //将元素逐个插入到list中 for (Object o : a) { @SuppressWarnings("unchecked")Ee= (E) o; Node<E> newNode = newNode<>(pred, e, null); if (pred == null) first = newNode; else pred.next = newNode; pred = newNode; } //如果succ是null则, last=pred (last指向最后一个非空元素) if (succ == null) { last = pred; } else { //如果succ不为空, 那么将pred和succ连接起来. pred.next = succ; succ.prev = pred; } //size增加number size += numNew; //modCount自增. modCount++; returntrue; }
//位置检查. privatevoidcheckPositionIndex(int index) { if (!isPositionIndex(index)) thrownewIndexOutOfBoundsException(outOfBoundsMsg(index)); } /** * Tells if the argument is the index of a valid position for an * iterator or an add operation. */ privatebooleanisPositionIndex(int index) { return index >= 0 && index <= size; }
//移除首个元素并返回 public E removeFirst() { final Node<E> f = first; if (f == null) //注意first == null会抛出异常 thrownewNoSuchElementException(); //详细方法 return unlinkFirst(f); }
/** * Unlinks non-null first node f. * 整个函数将移除头部, 并将头部指向头部的下一个元素. */ private E unlinkFirst(Node<E> f) { // assert f == first && f != null; finalEelement= f.item; final Node<E> next = f.next; f.item = null; f.next = null; // help GC first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; return element; }
/** * Removes and returns the last element from this list. * * @return the last element from this list * @throws NoSuchElementException if this list is empty */ //移除末尾元素 public E removeLast() { final Node<E> l = last; if (l == null) //注意last == null会抛出异常 thrownewNoSuchElementException(); //详细方法 return unlinkLast(l); }
/** * Unlinks non-null last node l. */ private E unlinkLast(Node<E> l) { // assert l == last && l != null; finalEelement= l.item; final Node<E> prev = l.prev; l.item = null; l.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; modCount++; return element; }
/** * 移除函数. */ publicbooleanremove(Object o) { if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); returntrue; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); returntrue; } } } returnfalse; }
/** * Unlinks non-null node x. */ E unlink(Node<E> x) { // assert x != null; finalEelement= x.item; //当前 final Node<E> next = x.next; // 前向节点 final Node<E> prev = x.prev; // 后向节点
if (prev == null) { //边界 first = next; } else { prev.next = next; x.prev = null; }
if (next == null) { //边界 last = prev; } else { next.prev = prev; x.next = null; }
public E remove(int index) { checkElementIndex(index); //检查index是否在边界之内, 否则抛出数组越界异常. return unlink(node(index)); }
改
改就一个接口, 直接将制定的index上的元素置为指定的元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/** * Replaces the element at the specified position in this list with the * specified element. * * @param index index of the element to replace * @param element element to be stored at the specified position * @return the element previously at the specified position * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { checkElementIndex(index); Node<E> x = node(index); EoldVal= x.item; x.item = element; return oldVal; }
/** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E get(int index) { checkElementIndex(index); return node(index).item; } //注意这里返回是非空的 /** * Returns the (non-null) Node at the specified element index. */ Node<E> node(int index) { // assert isElementIndex(index);
if (index < (size >> 1)) { Node<E> x = first; for (inti=0; i < index; i++) x = x.next; return x; } else { Node<E> x = last; for (inti= size - 1; i > index; i--) x = x.prev; return x; } }
/** * Returns {@code true} if this list contains the specified element. * More formally, returns {@code true} if and only if this list contains * at least one element {@code e} such that * <tt>(o==null ? e==null : o.equals(e))</tt>. * * @param o element whose presence in this list is to be tested * @return {@code true} if this list contains the specified element */ publicbooleancontains(Object o) { return indexOf(o) != -1; } //索引指定对象o publicintindexOf(Object o) { intindex=0; //如果o是空的, 找到第一个null元素 if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) return index; index++; } //否则找到和o相等的元素,并返回index. } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) return index; index++; } } return -1; }