Transferred from: http://blog.csdn.net/wuchuanpingstone/article/details/6678653
Personal advice: The following article is an example of the way to explain ArrayList, LinkedList, but the best way is to look at the source code. In fact, ArrayList is a dynamic array, LinkedList is a linked list.
1.ArrayList is the realization of the data structure based on dynamic array, LinkedList data structure based on linked list.
2. For random access get and set,arraylist is better than LinkedList, because ArrayList can be randomly positioned, and the LinkedList to move the pointer step to move to the node. (Refer to arrays and linked lists for thought)
3. For new and deleted operations the add and remove,linedlist are the dominant, only need to modify the pointer, and ArrayList to move the data to fill the deleted object space.
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?
A Complexity of Time
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.
Let's say we have a large list of elements that are already sequenced, that the list might be of type ArrayList or LinkedList, and now we're looking at this list for binary search. The comparison list is ArrayList and LinkedList when the query speed, see the following program:
1 Packagecom.mangocity.test;2 Importjava.util.LinkedList;3 Importjava.util.List;4 ImportJava.util.Random;5 Importjava.util.ArrayList;6 Importjava.util.Arrays;7 Importjava.util.Collections;8 Public classtestlist ... { 9 Public Static Final intn=50000;Ten Public StaticList values; One Static... { AInteger vals[]=NewInteger[n]; -Random r=NewRandom (); - for(inti=0,currval=0;i<n;i++)... { thevals=NewInteger (currval); -Currval+=r.nextint (100) +1; - } -values=arrays.aslist (vals); + } - Static Longtimelist (List lst) ... { + Longstart=System.currenttimemillis (); A for(inti=0;i<n;i++)... { at intindex=Collections.binarysearch (LST, Values.get (i)); - if(index!=i) -SYSTEM.OUT.PRINTLN ("* * * * ERROR * * * *"); - } - returnSystem.currenttimemillis ()-start; - } in Public Static voidMain (String args[]) ... { -System.out.println ("ArrayList Consumption Time:" +timelist (NewArrayList (values)); toSystem.out.println ("LinkedList Consumption Time:" +timelist (NewLinkedList (values)); + } -}
I get the output is: ArrayList consumption time: 15
LinkedList consumption time: 2596
This result is not fixed, but basically ArrayList time is obviously less than linkedlist time. Therefore, it is not advisable to use LinkedList in this case. The binary lookup method uses the random access (randomaccess) 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.
Looking at an example, if we have a list that we want to do a lot of insertions and deletions, LinkedList is a good choice in this case. Consider an extreme example where we repeatedly insert an element at the beginning of a list:
1 Packagecom.mangocity.test;2 ImportJava.util.*; 3 Public classListdemo {4 Static Final intn=50000; 5 Static Longtimelist (List list) {6 Longstart=System.currenttimemillis ();7Object o =NewObject ();8 for(inti=0;i<n;i++) 9List.add (0, O); Ten returnSystem.currenttimemillis ()-start; One } A Public Static voidMain (string[] args) { -System.out.println ("ArrayList Time:" +timelist (NewArrayList ())); -System.out.println ("LinkedList Time:" +timelist (NewLinkedList ())); the } -}
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 to assign a record to the element and then adjust the 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:
1 Private Static class Entry {2 34 5 }
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:
Performance Summary:
- |
add () operation |
delete () operation |
insert operation |
index value operation |
Iterator value operation |
arraylist/vector/stack |
good |
poor |
difference |
excellent |
excellent |
LinkedList |
Good |
Good |
Good |
Poor |
Excellent |
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.
ArrayList, list differences in Java
List Collection
The list inherits from the collection interface. A list is an ordered collection of elements in a list that can be acquired/deleted/inserted based on the index (ordinal number: The position information of the element in the collection).
Unlike set sets, the list allows repeating elements. For E1 and E2 object elements that meet the E1.equals (E2) condition, they can exist in the list collection at the same time. Of course, there is also a list implementation class that does not allow the existence of duplicate elements.
At the same time, thelist also provides a listiterator () method that returns a Listiterator interface object, and the addition, deletion, and setting of the Listiterator add element, as compared to the iterator interface, and can be traversed forward or backward.
The relationship between list and collection:
java.util.Collection [I]
+--java.util.list [I]
+--java.util.arraylist [C]
+--java.util.linkedlist [C]
+--java.util.vector [C]
+--java.util.stack [C]
The implementation classes of the list interface are mainly Arraylist,linkedlist,vector,stack and so on.
Parent-child relationships.
The list is an interface that ArrayList inherits with this interface and implements it.
Usually use ArrayList when using. You don't use a list. This can be used: List List = new ArrayList ();
Collection interface
Collection is the most basic set interface, and a collection represents a set of object, the collection element (Elements). Some collection allow the same elements while others do not. Some can sort and others can't. The Java SDK does not provide classes that inherit directly from collection, and the classes provided by JAVASDK are "sub-interfaces" such as list and set that inherit from collection.
All classes that implement the collection interface must provide two standard constructors: a parameterless constructor is used to create an empty collection, and a constructor with a collection parameter is used to create a new collection. This new collection has the same elements as the incoming collection. The latter constructor allows the user to copy a collection.
How do I traverse every element in the collection? Regardless of the actual type of collection, it supports a iterator () method that returns an iteration that uses the iteration to access each element of the collection one at a time. Typical usage is as follows:
Iterator it = Collection.iterator (); Get an iteration child
while (It.hasnext ()) {
Object obj = It.next (); Get the next element
}
The two interfaces that are derived from the collection interface are list and set.
List interface:
The list is an ordered collection, using this interface to precisely control where each element is inserted. The user is able to access the elements in the list using an index (where the element is positioned in the list, similar to an array subscript), similar to an array of java.
Unlike the set mentioned below, the list allows the same elements.
In addition to the iterator () method, which has the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface. Listiterator has a number of add () methods that allow you to add, delete, set elements, and traverse forward or backward.
the common classes that implement the list interface are Linkedlist,arraylist,vector and stacks.
LinkedList class
The LinkedList implements a list interface that allows null elements. Additionally LinkedList provides an additional Get,remove,insert method at the first or the tail of the LinkedList. These operations make the LinkedList available as a stack (stack), queue, or two-way queue (deque).
Note LinkedList does not have a synchronization method. If multiple threads access a list at the same time, you must implement access synchronization yourself. One workaround is to construct a synchronized list when the list is created:
List List = Collections.synchronizedlist (new LinkedList (...));
ArrayList class
ArrayList implements a variable-size array. It allows all elements, including null. ArrayList is not synchronized.
Size,isempty,get,set method run time is constant. But the Add method cost is the allocated constant, and adding n elements requires an O (n) time. Other methods run at a linear time.
Each ArrayList instance has a capacity (capacity), which is the size of the array used to store the elements. This capacity automatically increases as new elements are added, but the growth algorithm is not defined. When you need to insert a large number of elements, you can call the Ensurecapacity method before inserting to increase the capacity of the ArrayList to improve insertion efficiency.
like LinkedList, ArrayList is also unsynchronized (unsynchronized).
Summarize
If it involves operations such as stacks, queues, and so on, you should consider using the list, for quick insertions, for deleting elements, should use LinkedList, and if you need to quickly randomly access elements, you should use ArrayList.
Try to return the interface rather than the actual type, such as returning a list instead of ArrayList, so that if you need to change ArrayList to LinkedList later, the client code does not have to be changed. This is for abstract programming.
ArrayList, linklist differences in Java