/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return {@code true} (as specified by {@link Collection#add}) */ publicbooleanadd(E e){ final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; // 拷贝原容器,长度加一 Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; // 将原容器引用指向新副本 setArray(newElements); returntrue; } finally { lock.unlock(); } }
/** * Removes the element at the specified position in this list. * Shifts any subsequent elements to the left (subtracts one from their * indices). Returns the element that was removed from the list. * * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index){ final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; E oldValue = get(elements, index); int numMoved = len - index - 1; // 如果要删除的是列表末端数据,拷贝前len-1个数据到新副本上,再切换引用 if (numMoved == 0) setArray(Arrays.copyOf(elements, len - 1)); else { // 否则,将除要删除元素之外的其他元素拷贝到新副本中,并切换引用 Object[] newElements = new Object[len - 1]; System.arraycopy(elements, 0, newElements, 0, index); System.arraycopy(elements, index + 1, newElements, index, numMoved); setArray(newElements); } return oldValue; } finally { lock.unlock(); } }
public E get(int index){ return get(getArray(), index); }