ArrayList, Vector, linkedlist the difference and its advantages and disadvantages? Reproduced

Source: Internet
Author: User

Original link: http://blog.csdn.net/wangzff/article/details/7296648

Arraylist,linkedlist,vestor these three classes implement the Java.util.List interface, but they have their own different characteristics, mainly as follows:

First, the synchronization of

Arraylist,linkedlist are not synchronized, while vestor are synchronous. So if thread safety is not required, you can use ArrayList or LinkedList to save the overhead of synchronizing. But in the case of multithreading, sometimes you have to use vectors. Of course, there are some ways to package arraylist,linkedlist, so that they can also be synchronized, but the efficiency may be reduced.

Ii. Data growth
From the internal implementation mechanism, ArrayList and vectors are stored using the array form of OBJEC. When you add elements to both types, if the number of elements exceeds the current length of the internal array, they all need to extend the length of the internal array, and vector automatically grows the array length by default, ArrayList is the original 50%. So in the end you get this collection that takes up more space than you actually need. So if you're going to save a lot of data in a collection then there are some advantages to using vectors, because you can avoid unnecessary resource overhead by setting the initialization size of the collection.

Iii. efficiency of retrieving, inserting, and deleting objects

In ArrayList and vectors, retrieving an object from a specified position (with index), or inserting or deleting an object at the end of the collection, can be represented as O (1). However, if an element is added or removed elsewhere in the collection, the time spent will grow linearly: O (n-i), where n represents the number of elements in the collection, and I represents the index position at which the element is incremented or removed. Why is that? It is assumed that all elements after the first and second elements of the collection will perform the displacement of (N-i) objects when performing the above operations.
In LinkedList, the time it takes to insert or delete an element anywhere in the collection is the same as-O (1), but it is slower when indexing an element, O (i), where I is the index position.

Generally everyone knows the general difference between ArrayList and LinkedList:
     1.arraylist is the implementation of a dynamic array-based data structure, LinkedList based on the data structure of the linked list.
     2. For random access get and set,arraylist feel better than LinkedList because LinkedList want to move the pointer.
     3. Add and Remove,linedlist for new and deleted operations are the dominant, because ArrayList is moving the data.

ArrayList and LinkedList are two collection classes that store a series of object references (references). For example, we can use ArrayList to store a series of string or integer. So what's the difference in performance between ArrayList and LinkedList? When should I use ArrayList when should I use LinkedList?


One. Time Complexity
The first point is that ArrayList's internal implementation is based on an array of objects, so when it uses the Get method to access any element in the list (random access), it is faster than LinkedList. The Get method in LinkedList is checked from one end of the list in order until the other end. For LinkedList, there is no faster way to access a specified element in the list. The
assumes that we have a large list of elements that are already sorted, that the list may be of type ArrayList or LinkedList type, and now we are looking at this list for binary search, The comparison list is ArrayList and LinkedList when the query speed, see the following program:

Package com.mangocity.test;   Import java.util.LinkedList;   Import java.util.List;   Import Java.util.Random;   Import java.util.ArrayList;   Import Java.util.Arrays;   Import java.util.Collections; public class testlist ...          {public static final int n=50000;          public static List values; Static ...              {Integer vals[]=new integer[n];              Random r=new random (); for (int i=0,currval=0;i<n;i++) ...                {vals[i]=new Integer (currval);            Currval+=r.nextint (100) +1;        } values=arrays.aslist (Vals); } Static Long Timelist (List lst) ...            {long Start=system.currenttimemillis (); for (int i=0;i<n;i++) ...                {int Index=collections.binarysearch (LST, Values.get (i));            if (index!=i) System.out.println ("* * * * * * * * * *");        } return System.currenttimemillis ()-start; } public static void main (String aRgs[]) ...            {System.out.println ("ArrayList Consumption Time:" +timelist (new ArrayList (values));        System.out.println ("LinkedList Consumption Time:" +timelist (new LinkedList (values));    }   }

  I get output is: ArrayList consumption time:
                  LinkedList consumption time: 2596
This result is not fixed, but basically ArrayList time is significantly less than linkedlist time. Therefore, it is not advisable to use LinkedList in this case. The binary lookup method uses the random access policy, while LinkedList is not supported for fast random access. The amount of time spent on a random access to a linkedlist is proportional to the size of the list. Accordingly, the time spent in random access in ArrayList is fixed.
does this mean that ArrayList is always better than linkedlist performance? This does not necessarily mean that in some cases the performance of LinkedList is better than that of ArrayList, and some algorithms are more efficient when implemented in LinkedList. For example, if you use the Collections.reverse method to invert a list, its performance will be better.
Look at an example, join us have a list, to do a lot of insertions and deletions, in this case linkedlist is a better choice. Consider an extreme example where we repeatedly insert an element at the beginning of a list:

package com.mangocity.test;   Import java.util.*;        public class Listdemo {static final int n=50000;        Static long Timelist (list list) {long start=system.currenttimemillis ();        Object o = new Object ();        for (int i=0;i<n;i++) list.add (0, O);        Return System.currenttimemillis ()-start;             public static void Main (string[] args) {System.out.println ("ArrayList Time:" +timelist (New ArrayList ()));        System.out.println ("LinkedList Time:" +timelist (New LinkedList ())); }   }   

At this point my output is: ArrayList time: 2463


LinkedList Time: 15
This is in contrast to the result of the previous example, when an element is added to the beginning of ArrayList, all existing elements are moved back, which means the overhead of data movement and replication. Conversely, adding an element to the beginning of LinkedList is simply not an element that allocates a record and then adjusts two connections. The overhead of adding an element at the beginning of the LinkedList is fixed, while the overhead of adding an element at the beginning of ArrayList is proportional to the size of the ArrayList.


Two Complexity of space
There is a private inner class in LinkedList, which is defined as follows:

private static class Entry {            Object element;            Entry Next;            Entry previous;        }   

Each entry object reference an element in the list, along with its previous element and the next element in LinkedList. A LinkedList object with 1000 elements will have 1000 entry objects linked together, each of which corresponds to an element in the list. In this case, there will be a significant space overhead in a linkedlist structure because it stores information about the 1000 entity objects.
ArrayList uses a built-in array to store elements, and the starting capacity of this array is 10. When the array needs to grow, the new capacity is obtained as follows: the new capacity = (old capacity *)/2+1, which means that each capacity will probably increase by 50%. This means that if you have a ArrayList object with a large number of elements, then eventually there will be a lot of wasted space, and this waste is caused by the way ArrayList works itself. If there is not enough space to hold the new element, the array will have to be reassigned so that new elements can be added. Redistribution of the array will result in a dramatic decrease in performance. If we know how many elements a ArrayList will have, we can construct a method to specify the capacity. We can also remove wasted space after the ArrayList is allocated through the TrimToSize method.


Three Summarize
ArrayList and LinkedList have their own advantages and disadvantages in performance, and each has its own applicable place, which can be described as follows:
1. For ArrayList and LinkedList, the overhead of adding an element at the end of the list is fixed. For ArrayList, the main point is to add an entry in the internal array, pointing to the element being added, which may occasionally cause the array to be redistributed, whereas for LinkedList, the overhead is uniform, allocating an internal entry object.

2. Inserting or deleting an element in the middle of a ArrayList means that the remaining elements in the list will be moved, while the overhead of inserting or deleting an element in the middle of the linkedlist is fixed.


3. LinkedList does not support efficient random element access.


4. ArrayList space waste is mainly reflected in the end of the list to reserve a certain amount of space, and the space cost of LinkedList is reflected in its every element needs to consume considerable space


It can be said that using ArrayList provides better performance when the action is to add data after a column of data rather than in front or in the middle, and to randomly access its elements, and when your action is to add or delete data in front or in the middle of a column of data, and to access its elements sequentially, You should use the LinkedList.

So, if you just look for elements in a particular location or only add and remove elements at the end of the collection, you can use either a vector or a ArrayList. If you are inserting or deleting other specified locations, it is best to select LinkedList

ArrayList, Vector, linkedlist the difference and its advantages and disadvantages? Reproduced

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.