[Java] -List underlying collection


1 #####. Collection
Iterable interface in Java Map interface accounting system in the main position, substantially all of the data structures are based on the two interfaces, one is a linear iteration may be a hash table.

Seen by the figure, Collection Interface system as set parent interface, Map hash table system as an interface.

The main source to provide a method of collection Collection:


public interface Collection<E> extends Iterable<E> {
    int size();  // 集合大小
    boolean isEmpty(); // 是否为空
    boolean contains(Object o); // 是否包含某个元素
    Iterator<E> iterator(); // 返回迭代器
    Object[] toArray(); // 返回 Object 数组
    <T> T[] toArray(T[] a); // 返回指定泛型的数组
    boolean add(E e); // 添加一个元素,返回是否添加成功
    boolean remove(Object o); // 移除一个元素,返回是否添加成功
    boolean containsAll(Collection<?> c); // 是否包含另一个集合
    boolean addAll(Collection<? extends E> c); // 将另一个集合添加到当前集合
    boolean removeAll(Collection<?> c); // 移除当前集合的元素,返回集合是否被修改过
    default boolean removeIf(Predicate<? super E> filter); // 根据添加移除元素
    boolean retainAll(Collection<?> c); // 仅保留存在于给定集合的元素,返回集合是否被修改过
    void clear(); // 清空集合
    boolean equals(Object o);  // 判断是否相等
    int hashCode();	 // 返回hash值
}

#####2. List

  1. Characteristic data stored: storing an ordered, repeatable data.
  2. Common implementation class:
  • Collection Interface: single set, for storing an object a
  • Interface List: storing sequence, reproducible data. -> "dynamic" array, replacing the original array
  • ArrayList: List as a main interface implementation class; thread-safe, high efficiency; underlayer using Object [] elementData storage, with increasing dynamic expansion element
  • LinkedList: For frequent insertion, deletion, use of such higher efficiency than the ArrayList; underlying storage using a doubly linked list, as the element while the rear end of the growing list of the node

###### 2.1 List Interface

#List方法
A:添加功能
  boolean add(E e):向集合的尾部添加一个元素
* void add(int index, E element):在指定位置添加元素
  boolean addAll(Collection<? extends E> c):在集合中尾部添加一个集合。
* boolean addAll(int index, Collection<? extends E> c);// 在集合指定位置添加一个集合。

B:删除功能
  void clear():删除集合中的所有元素
* E remove(int index):删除集合指定位置的元素,并把删除的元素返回
  boolean remove(Object o):删除集合中指定的元素
  boolean removeAll(Collection<?> c):删除两个集合的交集 。
* default void replaceAll(UnaryOperator<E> operator) // 将集合中的元素特换成指定元素

C:修改功能
  void clear(); // 清空集合元素
   E set(int index, E element):把指定索引位置的元素修改为指定的值,返回修改前的值。

D:获取功能
*   E get(int index):获取指定位置的元素
* int indexOf(Object o);// 获取元素在集合中首次出现的位置,获取不到返回 -1
* int lastIndexOf(Object o);// 获取元素在集合中最后出现的位置,获取不到返回 -1
* List<E> subList(int fromIndex, int toIndex);// 截取指定区间位置内的集合

E:迭代器
   Iterator iterator():获取集合中每一个元素。
*  ListIterator<E> listIterator(int index); // 获取集合从特定位置开始的每个元素

F:判断功能
  boolean isEmpty():判断集合是否为空:size==0
  boolean contains(Object o):判断集合中是否存在指定的元素。
  boolean containsAll(Collection<?> c):判断集合C是否为当前集合的子集。
*  boolean retainAll(Collection<?> c); // 求两个集合的交集,并将交集赋值给当前集合,若集合有变化则返回true,若两集合相等则返回false
  boolean equals(Object o);// 判断两个集合是否相等:集合长度、元素、元素位置

G:数组功能
  int hashCode();
  int size():获取集合中的元素个数
* default void sort(Comparator<? super E> c)// 对集合进行特定排序

H:把集合转换成数组
  Object[] toArray():把集合变成数组。
  public <T> T[] toArray(T[] a) ;
2.2 ArrayList class

ArrayList Java Collections Framework is the most used in a class, is an array queue, thread-safe collection.

It inherits AbstractList, implements List, RandomAccess, Cloneable, Serializable interface.

  1. ArrayList implement List, List collection framework has been the basis of function;
  2. ArrayList achieve the RandomAccess, to obtain rapid random access memory functional element, the RandomAccess is a marker interface, there is no way;
  3. ArrayList achieve the Cloneable, to obtain a clone () method may be implemented cloning function;
  4. ArrayList achieve the Serializable, representation can be serialized, serialization to transfer protocols typical application is hessian.

2.2.1 ArrayList class structure features:

  • Capacity is not fixed, as capacity increases dynamically expansion (substantially not reach the threshold value)
  • Ordered set (the order of insertion sequence == output)
  • Inserted elements may be null
  • CRUD more efficient (relative to LinkedList is)
  • Thread safe

2.2.2 common method ArrayList class
ArrayList List collection frame base function implemented, the implementation logic implemented in all methods, no new public methods, the new method is also only help private processing logic.

  • 1.ArrayList global variables
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{   
    private static final int DEFAULT_CAPACITY = 10; // 默认初始化容量为10

    private static final Object[] EMPTY_ELEMENTDATA = {}; // 创建一个空数组

    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; // 创建一个拥有默认容量为10的空数组

    transient Object[] elementData; // ArrayList底层使用数组进行存储。设置为DEFAULTCAPACITY_EMPTY_ELEMENTDATA的list,在首次调用add方法时,容量会扩容为10.

    private int size; // ArrayList的大小,即元素的个数
    
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // list的最大容量
    }
  • 2.ArrayList constructor

ArrayList three constructors:

  1. No-argument: an empty array, the array is created by default when you call the method capacity of 10
  2. Specifies length list: create an array of the specified constants
  3. Specified elements: the capacity to create an array of elements set of size and length determined
     // 1. 创建空数组,调用方法时默认创建数组的容量为10
     public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    
    // 2. 创建指定长度的list:底层创建指定长度的数组
     public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity]; // 创建指定长度的数组
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA; // 创建空数组
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
    
     // 3. 创建一个包含指定元素的集合列表
     public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class); // 将集合转换成数组存储
        } else {
            // replace with empty array.
            this.elementData = EMPTY_ELEMENTDATA;// 创建空数组
        }
    }
  • 3 ArrayList add elements and expansion
    ArrayList add method There are two major categories:
  1. Add list or set of trailing elements: (<? Extends E> Collection c) add (E e), addAll
  2. Add the specified location or element in the list set: add (int index, E element), addAll (int index, Collection <? Extends E> c)

After Class second method involves the shift of the specified position of the element, the source element is mainly System.arraycopy method called after shifting and assignment; Method of Class 1 directly added at the end, does not involve moving elements.

ArrayList will first check when calling the method add the current capacity meets the size + 1 (numNew) demand, if you continue to add to meet, if not met for expansion.

Note: ArrayList allows adding null, while the size + 1; emptying the collection element is set to null, size = 0

 // 1.在list尾部添加元素
    public boolean add(E e) {
        ensureCapacityInternal(size + 1); // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
     //2.将集合c元素添加到在list尾部
     public boolean addAll(Collection<? extends E> c){
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew); // Increments modCount
        System.arraycopy(a, 0, elementData, size, numNew);
        size += numNew;
        return numNew != 0;
    }

    //3.在指定位置插入元素
     public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1); // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
    
 //4.在指定位置插入集合元素
     public boolean addAll(int index, Collection<? extends E> c){
        rangeCheckForAdd(index);
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew); // Increments modCount
        int numMoved = size - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew,numMoved);
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }

ArrayList expansion logic:

  1. The minimum capacity calculation: minCapacity = size + 1 (numNew)
  • If the list is DEFAULTCAPACITY_EMPTY_ELEMENTDATA, the required minimum capacity: Math.max (DEFAULT_CAPACITY, minCapacity)
  • Otherwise, the minimum capacity required: minCapacity
  1. The current capacity and minimum capacity (be minCapacity) determines:
  • If the current capacity of> minimum capacity (minCapacity), is normally added
  • If the current capacity <minimum capacity (minCapacity), expansion is performed
  1. Expansion:
  • The current capacity expanded to 1.5 times to obtain a new capacity
  • If the new capacity> minimum capacity (minCapacity), the capacity of the newly set up; if the new capacity <minimum capacity (minCapacity), then the new capacity = minimum capacity (be minCapacity)
  1. The new capacity threshold determination: MAX_ARRAY_SIZE
  • If the new capacity <MAX_ARRAY_SIZE, the establishment of new capacity
  • If the new capacity of more than MAX_ARRAY_SIZE
    • If the minimum capacity (minCapacity) <MAX_ARRAY_SIZE, then the new capacity = MAX_ARRAY_SIZE
    • If the minimum capacity (minCapacity)> MAX_ARRAY_SIZE, then the new capacity = Integer.MAX_VALUE

Note: list current expansion is to copy elements to the new array and returns a new arrayelementData = Arrays.copyOf(elementData, newCapacity)

// 与扩容相关的方法
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
    
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    
     private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    
     private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }
    
     private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
  • 4.ArrayList intersection, difference
    removeAll and retainAll methods involve removing elements of the bottom are called batchRemove method, different parameters just passing
    processing logic batchRemove method:
    1. The qualified repositioning elements in the array (starting with index 0)
    2. After all screening, the remaining elements of the location is set to null
  // 删除两个集合的交集
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }
    // 保留两个集合的交集
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }
    
    // 集合操作过程
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
  • 5.ArrayList element is moved
    because ArrayList is contiguous address storage element, when the add or delete elements list (or set) at the specified location, after all the elements necessary to specify the position of a move forward or backward (or N bit).

ArrayList corresponding method are:

  1. add(int index, E element)、addAll(int index, Collection<? extends E> c)
  2. remove(int index)、removeRange(int fromIndex, int toIndex)、 remove(Object o)

Such methods are invoked System.arraycopy underlying method for mobile elements.

    // 1.在指定位置添加元素
     public void add(int index, E element) {
        rangeCheckForAdd(index);
        ensureCapacityInternal(size + 1); // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = element;
        size++;
    }
   // 2.在指定元素添加集合元素
   public boolean addAll(int index, Collection<? extends E> c) {
        rangeCheckForAdd(index);
        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityInternal(size + numNew); // Increments modCount
        int numMoved = size - index;
        if (numMoved > 0)
            System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
        System.arraycopy(a, 0, elementData, index, numNew);
        size += numNew;
        return numNew != 0;
    }
   // 3.删除指定位置的元素
    public E remove(int index);
     {
        rangeCheck(index);
        modCount++;
        E oldValue = elementData(index);
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--size] = null; // clear to let GC do its work
        return oldValue;
    }
    
      // 4.删除指定范围内的元素
     protected void removeRange(int fromIndex, int toIndex){
        modCount++;
        int numMoved = size - toIndex;
        System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex);
        for (int i = newSize; i < size; i++) {
            elementData[i] = null;
        }
        size = newSize;
    }
    
    // 5.删除指定元素
    public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }
   
   // 快速删除指定位置元素
   private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    } 
  • 6.ArrayList iterator
    ArrayList built two iterators: Itr, ListItr:
  1. Itr achieved Iterator interface, mainly for a set of operations that define the logic of the method hasNext, next, remove, etc.
  2. Itr ListItr inheritance class implements the interface ListIterator, mainly for the operation set list, that define the logical nextIndex, previous, previousIndex, set, add and other methods of

ArrayList built-implemented method of logic built AbstractList iterator iterator same logical process.

There are three ways to invoke ArrayList iterator: iterator (), listIterator (), listIterator (int index)

Note: When calling the iterator, you can not modify the operation of the original list; at the same time to set, add, remove methods can only do this once. Iterator logic embodied visible] [Detailed set iterator

   // 1.调用Itr迭代器
   public Iterator<E> iterator() {
        return new Itr();
    }
   // 2.调用listIterator迭代器    
   public ListIterator<E> listIterator() {
        return new ListItr(0);
    }
    // 3.指定位置开始调用listIterator迭代器       
    public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

  • 7.ArrayList common general approach
  1. Note that the number of elements in distinguishing ArrayList (size) and arrays capacity
  2. trimToSize () method for removing excess capacity, the number of elements equal to the new position of the array assigned to the current array.
  3. clone () method returns a new set of element positions equal to the number of
  4. clear () to set all the elements null, size = 0
  5. isEmpty () determines size == 0
   public boolean isEmpty() {
        return size == 0;
    }
    
*   E elementData(int index) {
        return (E) elementData[index];
    } 
    
    public int indexOf(Object o);// 返回元素在集合中第一次出现的位置,元素O可以为null,查找不到返回-1 
    // 去掉预留元素位置:使数组容量=数组元素个数(size)
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }
     //克隆当前集合为新的集合对象
*   public Object clone(){ 
        try {
            ArrayList<?> v = (ArrayList<?>) super.clone();
            v.elementData = Arrays.copyOf(elementData, size);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }
     
    public void clear() {
        modCount++;
        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }

3 #####. Queue
###### 3.1.Queue Interface

Queue interface extends the Collection interface, on the basis of the basic operation of the interface Collection on the new add, get, delete methods, each method has two modes: 1 throw an exception if the operation fails; 2 If the operation fails to return null.. or false.


public interface Queue<E> extends Collection<E> {

 #添加元素

    boolean add(E e);// 添加成功返回true;如果因为容量有限添加失败,则抛出异常IllegalStateException

    

    boolean offer(E e);// 添加成功返回true,否则返回false。

    

    #删除头元素

    E remove();// 删除头元素,如果队列为空,抛出异常NoSuchElementException

    

    E poll();// 获取头元素,如果队列为空返回null

    

    #查询头元素,并不删除头元素

    E element();// 查询头元素,如果队列为空抛出异常NoSuchElementException

    

    E peek();// 查询头元素,如果队列为空返回null 

}

3.2.Deque Interface

Deque interface methods can be divided into:

  • . For deque: 1 in the first queue, last for add, remove, 6 categories of methods get; 2 delete specific elements:. RemoveFirstOccurrence (Object o), removeLastOccurrence (Object o).
  • For queue: add, remove, 3 categories of methods get.
  • For the stack: push, 2 Ge methods of pop
  • . For a set of: obtaining a particular element or deleted: contains (Object o), remove (Object o); 2 the number of elements:. Size (); 3 iterator:. Iterator (), descendingIterator ()

Interface Deque Features:
Deque Queue interface extends the interface, so it comes to add, remove, get operation provides two ways: 1 throw exception operation failed; 2 operation failed return null or false...
Deque interface to access the elements do not support the index.

public interface Deque<E> extends Queue<E> {
   /** 双端队列的方法
   */
#添加元素至队列头部
   void addFirst(E e);// 添加成功返回true,若因容量受限添加失败,抛出异常:IllegalStateException
   
   boolean offerFirst(E e); // 添加成功返回true,否则返回false
   #添加元素至队列尾部
   void addLast(E e);// 添加成功返回true,若因容量受限添加失败,抛出异常:IllegalStateException
   
   boolean offerLast(E e);// 添加成功返回true,否则返回false
   
   #删除队列头元素
   E removeFirst();// 删除头元素,如果队列为空,抛出异常:NoSuchElementException
   
   E pollFirst();// 删除头元素,如果队列为空返回null

   #删除队列尾元素
   E removeLast();// 删除尾元素,如果队列为空,抛出异常:NoSuchElementException
   
   E pollLast();// 删除尾元素,如果队列为空返回null
   
   #获取队列头元素
   E getFirst();// 获取头元素,如果队列为空,抛出异常:NoSuchElementException
   
   E peekFirst();// 获取头元素,如果队列为空返回null

   #获取队列尾元素
   E getLast();// 获取尾元素,如果队列为空,抛出异常:NoSuchElementException

   E peekLast();// 获取尾元素,如果队列为空返回null
   
   #将队列首次出现的元素o删除
   boolean removeFirstOccurrence(Object o);// 如果删除成功返回true
   
   #将队列最后出现的元素o删除
   boolean removeLastOccurrence(Object o);// 如果删除成功返回true

   /** Queue接口方法
   */
#在队列尾部添加元素
   boolean add(E e);// 添加成功返回true;如果因为容量有限添加失败,则抛出异常IllegalStateException
   
   boolean offer(E e);// 添加成功返回true,否则返回false。
   
   #删除队列尾部元素
   E remove();// 如果队列为空,抛出异常NoSuchElementException
   
   E poll();// 如果队列为空返回null
   
   #查询队列头元素,并不删除头元素
   E element();// 如果队列为空抛出异常NoSuchElementException
   
   E peek();// 如果队列为空返回null  
   
   /** 栈Stack方法,只在栈顶进行元素的入栈和出栈
   */
   #元素入栈
   void push(E e);// 入栈成功返回true,如果因为容量受限,抛出异常:IllegalStateException

#元素出栈
   E pop();// 如果队列为空,抛出异常:NoSuchElementException
   
   /** 集合Collection方法
   */
   # 删除队列首次出现的元素o
   boolean remove(Object o);// 删除成功返回true。 方法等同于 removeFirstOccurrence(Object o) 方法
   
   # 判断队列中是否包含元素o
   boolean contains(Object o);// 如果包含返回true,否则返回false
   
   # 队列元素个数
   public int size();

#队列迭代器
   Iterator<E> iterator(); 
   
   #队列反转的迭代器
   Iterator<E> descendingIterator();

}
3.3.LinkedList

LinkedList is a doubly linked list, each node has a reference point before and after the node. In ArrayList, a LinkedList lower compared to random access efficiency.

It inherits AbstractSequentialList, implements List, Deque, Cloneable, Serializable interface.
(1) LinkedList realized List, obtained List collection frame base functionality;
(2) the LinkedList implemented Deque, Deque is a double-ended queue, i.e. either FIFO, after but also first-out, said simpler that both in the first portion additive element may be added elements to the end;
(. 3) the LinkedList achieve the Cloneable, to obtain a clone () method may be implemented cloning capability;
(. 4) the LinkedList implement the serializable, representation can be serialized, serialization to the transmission, typically the application is the hessian protocol.

2. The common method


3. source code analysis

       LinkedList list = new LinkedList(); 内部声明了Node类型的first和last属性,默认值为null
       list.add(123);//将123封装到Node中,创建了Node对象。
       其中,Node定义为:体现了LinkedList的双向链表的说法
       private static class Node<E> {
            E item;
            Node<E> next;
            Node<E> prev;
            Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
            }
        }

###### 3.4. ArrayList and LinkedList compare
the main difference is the difference between arrays and linked lists before LinkedList and ArrayList.
Array assignment queries and faster, because you can mark by an array of direct access to the specified location.

To delete the list and increase faster because directly by modifying the pointer list (Java no pointer in here can be simply understood as a guideline. In fact, is designated by Node node variable) add or delete elements.

So, LinkedList and ArrayList compared deletions faster. But the query and modify the value of slow. Meanwhile, LinkedList also implements the Queue interface, so he also offers offer (), peek (), poll () methods.
https://www.jianshu.com/p/63b01b6379fb

4 #####. Vector
Vector and ArrayList, are achieved through the array, but Vector is thread-safe. And compared to ArrayList, which are many ways to ensure the security thread through the synchronization (synchronized) process.

If your program does not involve security thread, then use ArrayList is a better option (because the use of Vector synchronized, will inevitably affect the efficiency).

There is also a difference between the two is not the same expansion strategy. When List was first created, there will be an initial size, with the increasing elements to the List, the List when the capacity is not enough time to think it will be expansion. Automatic double the increase of the original length of the array of default under Vector, ArrayList growth of the original 50%.

##### 5. How to select
if it comes to multi-threaded, then select Vector (Of course, you can also use your own ArrayList and synchronization).

If you do not relate to multi-thread, ArrayList selected from the LinkedList. LinkedList more suitable for inserting or deleting (a characteristic list) from the intermediate. ArrayList is more suitable to retrieve and insert or delete (characteristic of the array) end.

Link: https: //www.jianshu.com/p/1149f1bf1736

Published 18 original articles · won praise 0 · Views 713

Guess you like

Origin blog.csdn.net/qq_39953750/article/details/104758632