publicstaticvoidarraycopy(Object src, int srcOfs, Object dest, int destOfs, int len) { if (src == null || dest == null) { thrownewNullPointerException(); }
Class<?> srcType = src.getClass(); Class<?> destType = dest.getClass(); if (!srcType.isArray() || !destType.isArray()) { thrownewArrayStoreException("Must be array types"); }
Class<?> srcComp = srcType.getComponentType(); Class<?> destComp = destType.getComponentType(); if (srcComp.modifiers != destComp.modifiers || (srcComp.isPrimitive() && !srcComp.equals(destComp))) { thrownewArrayStoreException("Array types must match"); } intsrclen= getArrayLength(src); intdestlen= getArrayLength(dest); if (srcOfs < 0 || destOfs < 0 || len < 0 || srcOfs + len > srclen || destOfs + len > destlen) { thrownewIndexOutOfBoundsException(); } /* * If the arrays are not references or if they are exactly the same type, we * can copy them in native code for speed. Otherwise, we have to copy them * in Java so we get appropriate errors. */ if ((!srcComp.isPrimitive() || srcComp.isArray()) && !srcType.equals(destType)) { // copy in Java to make sure we get ArrayStoreExceptions if the values // aren't compatible Object[] srcArray = (Object[]) src; Object[] destArray = (Object[]) dest; if (src == dest && srcOfs < destOfs) { // TODO(jat): how does backward copies handle failures in the middle? // copy backwards to avoid destructive copies srcOfs += len; for (intdestEnd= destOfs + len; destEnd-- > destOfs;) { destArray[destEnd] = srcArray[--srcOfs]; } } else { for (intdestEnd= destOfs + len; destOfs < destEnd;) { destArray[destOfs++] = srcArray[srcOfs++]; } } } else { nativeArraycopy(src, srcOfs, dest, destOfs, len); } }
publicvoidadd(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); } /** * 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++; }
/** * Inserts element e before non-null Node succ. */ voidlinkBefore(E e, Node<E> succ) { // assert succ != null; final Node<E> pred = succ.prev; final Node<E> newNode = newNode<>(pred, e, succ); succ.prev = newNode; if (pred == null) first = newNode; else pred.next = newNode; size++; modCount++; }
而链表因为他的存储是不连续的,改一下引用或者叫指针就ok了,所以速度很快。
但是链表查找是是非常慢的,特别是在中间的时候。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * 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; } }