//LinkedList get() 方法 /** * 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); //检查是否越界,和队列长度size比较 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; } }
//ArrayList 的 remove()方法 public E remove(int index) { rangeCheck(index);
modCount++; EoldValue= elementData(index);
intnumMoved= size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, //这里将数组往前复制 numMoved); elementData[--size] = null; // clear to let GC do its work
defaultvoidsort(Comparator<? super E> c) { Object[] a = this.toArray(); Arrays.sort(a, (Comparator) c); //这里说明 Collections的排序实际上调用Arrays的排序 ListIterator<E> i = this.listIterator(); for (Object e : a) { i.next(); i.set((E) e); } }
//Arrays.sort 方法 publicstatic <T> voidsort(T[] a, Comparator<? super T> c) { if (c == null) { //判断是否使用了比较器 sort(a); } else { //使用了就判断LegacyMergeSort(JDK1.6中使用) 是否开启 if (LegacyMergeSort.userRequested) legacyMergeSort(a, c); else//使用了比较器用 TimSort(是一种归并排序) TimSort.sort(a, 0, a.length, c, null, 0, 0); } }
//没有使用比较器,用优化了的 ComparableTimSort publicstaticvoidsort(Object[] a) { if (LegacyMergeSort.userRequested) legacyMergeSort(a); else ComparableTimSort.sort(a, 0, a.length, null, 0, 0); }