源码解析

add

  1. public boolean add(E e) {
  2. final ReentrantLock lock = this.lock;
  3. lock.lock();
  4. try {
  5. Object[] elements = getArray();
  6. int len = elements.length;
  7. Object[] newElements = Arrays.copyOf(elements, len + 1);
  8. newElements[len] = e;
  9. //将新的数组指向原来的引用
  10. setArray(newElements);
  11. return true;
  12. } finally {
  13. lock.unlock();
  14. }
  15. }

remove

  1. public E remove(int index) {
  2. final ReentrantLock lock = this.lock;
  3. lock.lock();
  4. try {
  5. Object[] elements = getArray();
  6. int len = elements.length;
  7. E oldValue = get(elements, index);
  8. int numMoved = len - index - 1;
  9. if (numMoved == 0)
  10. setArray(Arrays.copyOf(elements, len - 1));
  11. else {
  12. Object[] newElements = new Object[len - 1];
  13. System.arraycopy(elements, 0, newElements, 0, index);
  14. System.arraycopy(elements, index + 1, newElements, index,
  15. numMoved);
  16. setArray(newElements);
  17. }
  18. return oldValue;
  19. } finally {
  20. lock.unlock();
  21. }
  22. }