The difference analysis of ArrayList and linklist in Java _java

Source: Internet
Author: User
Tags static class

1.ArrayList is a data structure based on dynamic array, LinkedList based on the data structure of the linked list.
2. For random access get and set,arraylist is better than LinkedList, because ArrayList can be randomly positioned, and linkedlist to move the pointer step-by-step move to the node. (reference array and linked list to think about)
3. For additions and deletions, add and remove,linedlist are more dominant, and 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 strings or integers. So what are the differences in performance between ArrayList and LinkedList? When should you use ArrayList and when should you use LinkedList?

A Complexity of Time

First of all, the internal implementation of ArrayList is based on an array of objects, so it is faster than linkedlist to use the Get method to access any element in the list (random-access). 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 a list.

Let's say we have a big list of elements that are already sorted, the list may be ArrayList type or LinkedList type, and now we're doing a binary lookup on this list (binary search), The comparison list is ArrayList and LinkedList when the query speed, look at the following program:

Copy Code code as follows:

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=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 ("Wrong * * * * * * *");
}
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 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 random access (randomaccess) strategy used in the binary lookup method, while LinkedList does not support fast random access. The amount of time spent doing random access to a linkedlist is proportional to the size of the list. Correspondingly, 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 linkedlist performance is better than ArrayList, and some algorithms are more efficient when implemented in LinkedList. For example, if you use the Collections.reverse method to reverse a list, its performance will be better.

Look at such an example, if we have a list, we have to do a lot of insert and delete operations, in this case linkedlist is a better choice. Take a look at the extreme example below, and we repeat the insertion of an element at the beginning of a list:

Copy Code code as follows:

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 Consuming:" +timelist (New ArrayList ()));
System.out.println ("LinkedList time Consuming:" +timelist (New LinkedList ()));
}
}

At this point my output is: ArrayList time consuming: 2463

LinkedList Time consuming: 15

This is in stark contrast to the previous example, when an element is added to the beginning of the ArrayList, all existing elements are moved back, which means the cost of data movement and replication. Instead, adding an element to the 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, and the cost of adding an element at the beginning of the ArrayList is proportional to the size of the ArrayList.

Two Complexity of space

There is a private inner class in the LinkedList, 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 last and next element in LinkedList. A LinkedList object with 1000 elements will have 1000 linked entry objects, each of which corresponds to an element in the list. In this case, there will be a large space overhead in a linkedlist structure because it stores information about the 1000 entity objects.

ArrayList uses a built-in array to store the elements, and the initial capacity of the array is 10. When an array needs to grow, the new capacity is derived as follows: new capacity = (old capacity *3)/2+1, which means that the capacity will probably grow by 50% per second. This means that if you have a ArrayList object that contains a lot of elements, then eventually there will be a lot of space to be wasted, and that waste is caused by the way ArrayList works itself. If there is not enough space to hold the new elements, the array will have to be reassigned so that new elements can be added. Reassigning an array will result in a sharp drop in performance. If we know how many elements a ArrayList will have, we can construct a method to specify the capacity. We can also use the TrimToSize method to remove the wasted space after the ArrayList is allocated.

Three Summarize

ArrayList and LinkedList have their own strengths and weaknesses in their performance, and they all have their respective applications, which can generally be described as follows:

Performance Summary:

- Add () Action Delete () Action Insert Operation Index value Operation iterator value-taking operation
Arraylist/vector/stack Good Poor Poor Extremely excellent Extremely excellent
LinkedList Good Good Good Poor Extremely excellent

1. For ArrayList and LinkedList, the overhead of adding an element to the end of the list is fixed. For ArrayList, the main thing is to add an item to the internal array, point to the added element, and occasionally cause the array to be reassigned, and for LinkedList, the overhead is uniform, assigning an internal entry object.

2. Inserting or deleting an element in the middle of the ArrayList means that the remaining elements in the list are 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 list at the end of a certain amount of space reserved, and linkedlist space cost is reflected in its every element needs to consume considerable space

It can be said that when an operation is to add data after a column of data rather than in front or in the middle, and when you need to randomly access the elements, using ArrayList provides better performance; When you add or remove data in front of or in the middle of a column of data, and then access the elements in the order, You should use the LinkedList.

ArrayList, list differences in Java

List Collection
List inherits from the collection interface. A list is an ordered collection in which elements in a list can be obtained/deleted/inserted based on the index (ordinal number: the location of the element in the collection).

Unlike set sets, the list allows for duplicate elements. For E1 and E2 object elements that meet e1.equals (E2) conditions, they can exist in the list collection at the same time. Of course, there are also list implementation classes that do not allow duplicate elements to exist.
The list also provides a listiterator () method that returns a Listiterator interface object, listiterator adding elements, deleting, and setting, and traversing forward or backward, compared to the iterator interface.

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 relationship.
The list is an interface that ArrayList inherits from the interface and implements it.
Used in the general use of ArrayList. No use of the list. 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 be sorted and others not. The Java SDK does not provide classes that directly inherit from collection, and JAVASDK provides classes that inherit from collection such as list and set.
All classes that implement the collection interface must provide two standard constructors: parameterless constructors are used to create an empty collection, and a constructor for a collection parameter is used to create a new collection. This new collection has the same element as the incoming collection. The latter constructor allows the user to replicate 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 can be used to access each element of the collection one at a time. Typical usage is as follows:
Iterator it = Collection.iterator (); To get an iterative 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 can access the elements in the list, similar to the Java array, by using the index (the position of the element in the list, similar to the array subscript).
Unlike the set mentioned below, the list allows the same elements.
In addition to the iterator () method with the collection interface prerequisites, the list also provides a listiterator () method that returns a Listiterator interface, compared to the standard iterator interface, There are a number of add () listiterator that allow adding, deleting, setting elements, and traversing forward or backwards.
Common classes that implement the list interface are Linkedlist,arraylist,vector and stack.

LinkedList class
LinkedList implements the list interface, allowing null elements. Additionally LinkedList provides additional Get,remove,insert methods at LinkedList's header or tail. These operations enable LinkedList to be used as stacks (stack), queues (queue), or bidirectional queues (deque).
Note that 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 sized array. It allows all elements, including null. ArrayList is not synchronized.
The Size,isempty,get,set method runs at a constant time. However, the Add method cost is the allocated constant, and the time of O (n) is required to add n elements. The 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 can automatically increase 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 increase the insertion efficiency.
Like LinkedList, ArrayList is also unsynchronized (unsynchronized).

Summarize
If you are involved in stacks, queues, and other operations, you should consider using the list, for the need to quickly insert, delete elements, should use LinkedList, if you need to quickly randomly access elements, you should use ArrayList.
Try to return the interface instead of the actual type, such as returning a list instead of ArrayList, so that if you need to replace ArrayList with LinkedList later, the client code does not have to change. This is for abstract programming.

Related Article

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.