面试二十一、List

1、arrayList

  数组、线程不安全、扩容大小为原1.5倍

  查询快、增删慢

 1     /**
 2      * Increases the capacity to ensure that it can hold at least the
 3      * number of elements specified by the minimum capacity argument.
 4      *
 5      * @param minCapacity the desired minimum capacity
 6      */
 7     private void grow(int minCapacity) {
 8         // overflow-conscious code
 9         int oldCapacity = elementData.length;
10         int newCapacity = oldCapacity + (oldCapacity >> 1);
11         if (newCapacity - minCapacity < 0)
12             newCapacity = minCapacity;
13         if (newCapacity - MAX_ARRAY_SIZE > 0)
14             newCapacity = hugeCapacity(minCapacity);
15         // minCapacity is usually close to size, so this is a win:
16         elementData = Arrays.copyOf(elementData, newCapacity);
17     }

2、linkedList

  链表、线程不安全、默认增加到最后

  增删快、查询慢

  查询先判断当前要查到index和列表size的一半比大小,如果小于则从第一个开始,如果大于则从最后一个开始,然后遍历

 1     /**
 2      * Returns the (non-null) Node at the specified element index.
 3      */
 4     Node<E> node(int index) {
 5         // assert isElementIndex(index);
 6 
 7         if (index < (size >> 1)) {
 8             Node<E> x = first;
 9             for (int i = 0; i < index; i++)
10                 x = x.next;
11             return x;
12         } else {
13             Node<E> x = last;
14             for (int i = size - 1; i > index; i--)
15                 x = x.prev;
16             return x;
17         }
18     }

3、CopyOnWriteArrayList

  数组、线程安全

  将array设置为valatile,操作时用ReentrantLock加锁,元素操作完成后调用setArray将array值更新

 1     /** The array, accessed only via getArray/setArray. */
 2     private transient volatile Object[] array;
 3 
 4     /**
 5      * Appends the specified element to the end of this list.
 6      *
 7      * @param e element to be appended to this list
 8      * @return {@code true} (as specified by {@link Collection#add})
 9      */
10     public boolean add(E e) {
11         final ReentrantLock lock = this.lock;
12         lock.lock();
13         try {
14             Object[] elements = getArray();
15             int len = elements.length;
16             Object[] newElements = Arrays.copyOf(elements, len + 1);
17             newElements[len] = e;
18             setArray(newElements);
19             return true;
20         } finally {
21             lock.unlock();
22         }
23     }
24 
25     /**
26      * Sets the array.
27      */
28     final void setArray(Object[] a) {
29         array = a;
30     }

 

posted on 2021-08-30 11:05  Iversonstear  阅读(33)  评论(0编辑  收藏  举报

导航