Differences between ArrayList and LinkList in java

Source: Internet
Author: User

1. ArrayList is a dynamic array-based data structure. The ArrayList is based on the linked list data structure.
2. for Random Access to get and set, the ArrayList is better than the sorted list, because the ArrayList can be randomly located, and the sorted list needs to move the pointer to the node step by step. (Think about arrays and linked lists)
3. For add and remove operations, LinedList is dominant. You only need to modify the pointer, and ArrayList needs to move data to fill the space of the deleted object.

ArrayList and referlist are two collection classes used to store a series of object references ). For example, we can use ArrayList to store a series of strings or integers. So what is the performance difference between ArrayList and javaslist? When should I use ArrayList? When should I use the rule list?

I. Time Complexity

First, the key point is that the internal implementation of ArrayList is based on the basic object array. Therefore, when it uses the get method to access any element in the list (random-access ), it is faster than the upload list. The get method in the detail list starts to check from one end of the list in sequence until the other end. For the shortlist, there is no faster way to access a specified Element in the list.

Suppose we have a large list, and the elements in it are sorted. This list may be of the ArrayList type or the sorted list type, now we can perform binary search on this list. Compare the query speed when the list is ArrayList and sorted list. See the following program:

Copy codeThe Code is as follows: package com. mangocity. test;
Import java. util. Collections list;
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 ("*** error ***");
}
Return System. currentTimeMillis ()-start;
}
Public static void main (String args [])... {
System. out. println ("ArrayList time consumed:" + timeList (new ArrayList (values )));
System. out. println ("consumed list time consumed:" + timeList (new consumed list (values )));
}
}

The output I get is: ArrayList time consumed: 15

Worker list time consumed: 2596

This result is not fixed, but the ArrayList time is basically less than the time of the sorted list. Therefore, in this case, it is not recommended to use the consumer list. The random access policy used by the binary search method, while the random list does not support fast random access. The time consumed for Random Access to an external list is proportional to the size of the list. Correspondingly, the time consumed for random access in the ArrayList is fixed.

Does this indicate that ArrayList always performs better than javaslist? This is not necessarily the case. In some cases, the sorted list performs better than the ArrayList. Some algorithms are more efficient in the sorted list. For example, when you use the Collections. reverse Method to reverse the list, its performance will be better.

Let's look at this example. If we have a list and want to perform a large number of insert and delete operations on it, the optimize list is a good choice in this case. For example, in the next extreme example, we repeatedly insert an element at the beginning of a list:

Copy codeThe Code is 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 consumed:" + timeList (new ArrayList ()));
System. out. println ("consumed list time:" + timeList (new consumed list ()));
}
}

In this case, the output result is: ArrayList time consumed: 2463

Consumed list time: 15

This is opposite to the result of the previous example. When an element is added to the beginning of ArrayList, all existing elements will be moved back, which means the overhead of data movement and replication. On the contrary, to add an element to the consumer list, you can simply allocate a record to the element and adjust the two connections. The overhead of adding an element at the beginning of the ArrayList is fixed, and the overhead of adding an element at the beginning of the ArrayList is proportional to the size of the ArrayList.

Ii. space complexity

There is a private internal class in the tranquility list, which is defined as follows:

Private static class Entry {
Object element;
Entry next;
Entry previous;
}

One element in the reference list of each Entry object, and the previous and next elements in the reference list. A listing list object with 1000 elements will have 1000 Entry objects linked together. Each object corresponds to an element in the list. In this case, there will be a huge space overhead in a shortlist structure because it will store the information of the 1000 Entity objects.

ArrayList uses a built-in array to store elements. The initial capacity of this array is 10. when the array needs to increase, the new capacity is obtained according to the following formula: new capacity = (old capacity * 3)/2 + 1, that is, the capacity increases by about 50% each time. This means that if you have an ArrayList object that contains a large number of elements, a large amount of space will be wasted. This waste is caused by the ArrayList's working method. If there is not enough space to store new elements, the array will have to be re-allocated so that new elements can be added. Re-allocating arrays will result in a sharp reduction in performance. If we know how many elements an ArrayList will have, we can use the constructor to specify the capacity. We can also use the trimToSize method to remove the wasted space after the ArrayList is allocated.

Iii. Summary

ArrayList and History List have their own advantages and disadvantages in terms of performance and have their own applicability. In general, they can be described as follows:

Performance summary:

- Add () Operation Delete () Operation Insert operation Index value operation Iterator value operation
ArrayList/Vector/Stack Good Difference Difference Excellent Excellent
Shortlist Good Good Good Difference Excellent

1. For ArrayList and sort list, the overhead of adding an element at the end of the list is fixed. For ArrayList, an item is mainly added to the internal array, pointing to the added element. Occasionally, the array may be re-allocated. For the sorted list, this overhead is uniform, allocate an internal Entry object.

2. inserting or deleting an element in the middle of the ArrayList means that all the remaining elements in the list will be moved. the overhead of inserting or deleting an element in the middle of the List is fixed.

3. the random list does not support efficient random element access.

4. The space waste of ArrayList is mainly reflected in the reserved capacity space at the end of the list, while the space consumption of the list is reflected in that each of its elements consumes a considerable amount of space.

It can be said that when the operation is to add data after a column of data rather than in the front or middle, and needs to randomly access the elements, using ArrayList will provide better performance; when you add or delete data in front or middle of a column of data and access the elements in the column in sequence, you should use the sort list.

Differences between ArrayList and List in java

List Set
List inherits from the Collection interface. List is an ordered set. The elements in a List can be obtained, deleted, or inserted based on the index (sequence number: the position where the element is located in the set.

Unlike the Set, List allows repeated elements. Elements of e1 and e2 objects that meet the e1.equals (e2) conditions can exist in the List set at the same time. Of course, there are also List implementation classes that do not allow repeated elements.
At the same time, List also provides a listIterator () method to return a ListIterator interface object. Compared with the Iterator interface, ListIterator can add, delete, and set elements, it can also traverse forward or backward.

Relationship between List and Collection:
Java. util. Collection [I]
+ -- Java. util. List [I]
+ -- Java. util. ArrayList [C]
+ -- Java. util. Collections list [C]
+ -- Java. util. Vector [C]
+ -- Java. util. Stack [C]

The List interface implementation classes include ArrayList, List, Vector, and Stack.

Parent-child relationship.
List is an interface. ArrayList inherits from this interface and implements it.
ArrayList is generally used when it is used. List is not used. It can be used like this: List list = new ArrayList ();

Collection Interface
Collection is the most basic Collection interface. A Collection represents a group of objects, namely, Elements of the Collection ). Some collections allow the same elements while others do not. Some can be sorted, while others cannot. Java SDK does not provide classes that directly inherit from Collection. Java SDK provides classes that inherit from Collection "subinterfaces" such as List and Set.
All classes that implement the Collection interface must provide two standard constructor: A non-parameter constructor is used to create an empty Collection, A constructor with the Collection parameter is used to create a new Collection, which has the same elements as the imported Collection. The next constructor allows you to copy a Collection.

How to traverse every element in the Collection? Regardless of the actual type of Collection, it supports an iterator () method. This method returns an iterator, and each element in the Collection can be accessed one by one using this iterator. The typical usage is as follows:
Iterator it = collection. iterator (); // obtain an Iterator
While (it. hasNext ()){
Object obj = it. next (); // obtain the next element.
}
The two interfaces derived from the Collection interface are List and Set.

List interface:
List is an ordered Collection, which can be used to precisely control the insert position of each element. You can use an index (the position of an element in the List, similar to an array subscript) to access the elements in the List, which is similar to an array in Java.
Unlike the Set mentioned below, the List can have the same element.
In addition to the iterator () method required for the Collection interface, List also provides a listIterator () method to return a ListIterator interface. Compared with the standard Iterator interface, ListIterator has some more add () you can add, delete, and set elements to traverse forward or backward.
Common classes that implement the List interface include the List, ArrayList, Vector, and Stack.

Sort list class
The listlist interface allows null elements. In addition, the values list provides additional get, remove, and insert methods at the beginning or end of the values list. These operations enable the queue list to be used as a stack, queue, or two-way queue (deque ).
Note that the synchronized list method is not available. If multiple threads access a List at the same time, they must implement access synchronization by themselves. One solution is to construct a synchronized List when creating a List:
List list = Collections. synchronizedList (new Collections List (...));

ArrayList class
ArrayList implements an array of variable sizes. It allows all elements, including null. ArrayList is not synchronized.
Size, isEmpty, get, set method running time is constant. However, the overhead of the add method is the constant of the allocation. It takes O (n) to add n elements. The running time of other methods is linear.
Each ArrayList instance has a Capacity, that is, the size of the array used to store elements. This capacity can automatically increase with the addition of new elements, but the growth algorithm is not defined. When a large number of elements need to be inserted, you can call the ensureCapacity method before insertion to increase the ArrayList capacity to improve the insertion efficiency.
Like the synchronized list, ArrayList is also non-synchronous (unsynchronized ).

Summary
If operations such as stacks and queues are involved, you should consider using the List. For elements that need to be inserted and deleted quickly, you should use the random List. If you need to quickly access elements randomly, you should use the ArrayList.
Try to return the interface rather than the actual type. For example, if the List is returned rather than the ArrayList, the client code does not need to be changed if you need to replace the ArrayList with the explain List later. 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.