What happens with ArrayList or LinkedList it?

ArrayList and LinkedList frame is used to store a set of Java objects refer to two class list. ArrayList and LinkedList implement the List interface. List firstly make a simple understanding:

List (list) is an ordered collection of elements, also known as a sequence. It provides operation based on the position of the elements, helping to quickly access, add and delete elements in a list specific index. List of Collection and Iterable interface as the parent interface. It allows to store duplicates and null values, supports access the elements by index.

 

After reading this article to find out the problem: ArrayList and LinkedList What is the difference between the two? When should I use and when should we use ArrayList LinkedList it?

 

Below to add and delete elements LinkedList and ArrayList Comparing the differences

Add elements to the end of the list:

Adding elements to the tail end of the queue in an ArrayList following code:

public  Boolean the Add (E E) { 
   the ensureCapacity (size + 1'd); // make sure there is enough space inside the array 
   elementData of [size ++] = E; // the element added to the end of the array, is added to complete the 
   return  to true ;       
}

 

Performance of the ArrayList add () method depends on the ensureCapacity () method. Implement the ensureCapacity () as follows:

public VOD the ensureCapacity ( int be minCapacity) { 
  ModCount ++ ;
   int oldCapacity = elementData.length;
   IF (be minCapacity> oldCapacity) {     // if the array capacity is insufficient for expansion 
      Object [] = oldData elementData of;
       int newCapacity = (* oldCapacity. 3) / 2 + 1;   // expansion capacity of 1.5 times the original 
      IF (newCapacitty <be minCapacity)    // if the new capacity is less than the minimum capacity required, the minimum
                                                     // required capacity size 
         newCapacity be minCapacity =;   // for expansion array copy 
         elementData =Arrays.copyof(elementData,newCapacity);
  }
}

 

It can be seen that, as long as sufficient current capacity ArrayList, efficiency add () operation is very high. Only when the ArrayList demand for capacity exceeds the current size of the array, it requires expansion. The process of expansion, the array will be a lot of copy operations. When the array replication and, ultimately calling System.arraycopy () method, so add () operation efficiency is still quite high.

The LinkedList add () operation to achieve the following, it will be any element to a trailing end of the queue:

public  Boolean the Add (E E) { 
   AddBefore (E, header); // the element to a header preceding the 
   return  to true ; 
}

 

Wherein AddBefore () method to achieve the following:

private Entry<E> addBefore(E e,Entry<E> entry){
     Entry<E> newEntry = new Entry<E>(e,entry,entry.previous);
     newEntry.provious.next=newEntry;
     newEntry.next.previous=newEntry;
     size++;
     modCount++;
     return newEntry;
}

 

Visible, LinkeList since a linked list structure, there is no need to maintain capacity size. From this point on that, it has some performance advantages over ArrayList, however, each of the elements increased need to create a new Entry object, and more assignment. In frequent calls in the system, it will have some impact on performance.

Adding elements to the list anywhere

In addition to the elements to the end of the List, List interface also provides a method of inserting elements at an arbitrary position:void add(int index,E element);

Due to different implementation, ArrayList and LinkedList certain difference in performance in this method, since the ArrayList array-based implementation, the array is a contiguous memory space, if the insert elements at an arbitrary position of the array, will inevitably lead after the position all the elements need to be reordered, and therefore, the efficiency will be relatively low.

The following code is to achieve the ArrayList:

public void add(int index,E element){
   if(index>size||index<0)
      throw new IndexOutOfBoundsException(
        "Index:"+index+",size: "+size);
         ensureCapacity(size+1);
         System.arraycopy(elementData,index,elementData,index+1,size-index);
         elementData[index] = element;
         size++;
}

 

You can see each insertion operation, the array will be a copy. And this increase in the operating element when the end of the List is not present, a large number of array restructuring operation will cause poor system performance. List element and inserted in the position more forward, the greater the cost of the recombinant array.

The LinkedList at this time shows the advantages of:

public void add(int index,E element){
   addBefore(element,(index==size?header:entry(index)));
}

 

Seen, for LinkedList, the data is inserted at the end of the insertion List data is the same at any position, will not result in the insertion position of the front and method of reducing the insertion performance.

Delete any location element

For delete elements, List interface provides remove elements at any location method:

public E remove(int index);

 

ArrayList for it, remove () method and add () method is the same. After removing any position elements must restructure the array. ArrayList is implemented as follows:

public E remove(int index){
   RangeCheck(index);
   modCount++;
   E oldValue=(E) elementData[index];
  int numMoved=size-index-1;
  if(numMoved>0)
     System.arraycopy(elementData,index+1,elementData,index,numMoved);
     elementData[--size]=null;
     return oldValue;
}

 

It can be seen after deletion at every element of ArrayList effective, it must restructure the array. And delete the more forward position, the greater the overhead array restructuring.

public E remove(int index){
  return remove(entry(index));         
}
private Entry<E> entry(int index){
  if(index<0 || index>=size)
      throw new IndexOutBoundsException("Index:"+index+",size:"+size);
      Entry<E> e= header;
      if(index<(size>>1)){//要删除的元素位于前半段
         for(int i=0;i<=index;i++)
             e=e.next;
     }else{
         for(int i=size;i>index;i--)
             e=e.previous;
     }
         return e;
}

 

In the implementation of LinkedList, you must first find the elements to be removed through the loop. If you want to delete a position in the List of the first half, from front to back to find; if its position in the second half, looking from back to front. So whether you want to delete more forward or back by the elements are very efficient; but to remove the middle of the List element has been traversed almost half the List, in the case of List has a large number of elements, inefficient.

Capacity parameters

Capacity parameter is a characteristic parameter based on the performance of the array List Vector ArrayList and the like. It represents the size of the array initialization. When the number of elements exceeds the stored ArrayList its existing size. It will be for expansion, expansion of the array will cause the entire array to conduct a memory copy. Therefore, a reasonable array size helps to reduce the number of array expansion, thereby improving system performance.

public  ArrayList(){
  this(10);  
}
public ArrayList (int initialCapacity){
   super();
   if(initialCapacity<0)
       throw new IllegalArgumentException("Illegal Capacity:"+initialCapacity)
      this.elementData=new Object[initialCapacity];
}

 

ArrayList provides a constructor can develop the initial size of the array:

public ArrayList(int initialCapacity) 

 

List is to construct a one million elements, for example, when using the default initial size, relatively time consuming it is about 125ms, when the direct development of the array size of 100 million and same configuration ArrayList only relatively time-consuming 16ms.

Traverse the list

Traversing the list of operations is one of the most common list of operations, after JDK1.5, there are at least three commonly used way to navigate lists:

 

  • forEach operation

  • Iterator

  • for circulation.

 

String tmp;
long start=System.currentTimeMills();    //ForEach 
for(String s:list){
    tmp=s;
}
System.out.println("foreach spend:"+(System.currentTimeMills()-start));
start = System.currentTimeMills();
for(Iterator<String> it=list.iterator();it.hasNext();){    
   tmp=it.next();
}
System.out.println("Iterator spend;"+(System.currentTimeMills()-start));
start=System.currentTimeMills();
int size=;list.size();
for(int i=0;i<size;i++){                     
    tmp=list.get(i);
}
System.out.println("for spend;"+(System.currentTimeMills()-start));

 

1,000,000 has a configuration of a data ArrayList and the LinkedList equivalent, using the above test code, the test results:

[17] What is the situation with ArrayList or LinkedList it?

You can see, the easiest ForEach loop and not a very good performance, overall performance than ordinary iterator, but with the for loop by random access through the list, ArrayList entry is good, but the performance can not let LinkedList accepted, there is no way even wait for the end of the program. This is because when LinkedList for random access, there is always a traverse of a list. Performance is very poor, should be avoided.

to sum up

ArrayList and LinkedList advantages and disadvantages in performance, have their own local applicable, in general be described as follows:

 

1. For ArrayList and LinkedList terms, add an element to the end of the list are spent on fixed costs.

 

For ArrayList, primarily an increase in the internal array, pointing to the added elements, may occasionally lead to re-allocate the array;

 

While the LinkedList is concerned, this overhead is a unified, assign an internal Entry object.


2. Inserting or deleting an element in the middle of the ArrayList means that the remaining elements in the list will be moved; and inserting or deleting an element in the middle of LinkedList cost is fixed.


3. LinkedList does not support efficient random access elements.


4. Waste of space ArrayList is mainly reflected in some capacity reserved space at the end of the list list, and space spending LinkedList is reflected in each of its elements need to consume considerable space

 

It can be said: When the operation is to add the data behind a column of data, rather than in the front or in the middle and requires random access to its elements when using ArrayList have better performance; when the operation is in a front or intermediate data when you add or delete data, and access to its elements in the order, you should use a LinkedList.

Guess you like

Origin www.cnblogs.com/javazhiyin/p/11880771.html