ArrayList LinkedList Vector

Source: Internet
Author: User

ArrayList is an array-based implementation, with no capacity constraints.

When you delete an element, it does not reduce the size of the array, and you can call ArrayList's trimetosize () to reduce the capacity of the array.

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

Features: High efficiency of query, and deletion efficiency low lightweight thread insecure

LinkedList: List of the underlying with a bidirectional circular list

Features: Low query efficiency, high efficiency and deletion

Vector: Another class that implements the list interface with an array at the bottom

Features: Heavyweight, takes up more system overhead thread-safe


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 inner array, they all need to extend the length of the internal array, vector by default automatically increases the original array length, ArrayList is the original 50%, so finally you get This collection 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 realization of the data structure based on dynamic array, LinkedList data structure based on linked list.
2. For random access get and set,arraylist feel better than LinkedList, because linkedlist to move the pointer.
3. Add and Remove,linedlist are the dominant for new and deleted operations 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?


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 one of the elements 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:

Java code
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 (inti=0,currval=0;i<n;i++) ... {
Vals=newinteger (Currval);
Currval+=r.nextint (100) +1;
}

Values=arrays.aslist (Vals);
}

Static Long Timelist (List lst) ... {
Longstart=system.currenttimemillis ();
for (int i=0;i<n;i++) ... {
int Index=collections.binarysearch (Lst,values.get (i));
if (index!=i)
SYSTEM.OUT.PRINTLN ("* * * * * * * * *");
}
Returnsystem.currenttimemillis ()-start;
}
public static void Main (String args[]) ... {
System.out.println ("ArrayList Consumption Time:" +timelist (Newarraylist (values));
System.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 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 of this, joining us has a list of many insertions and deletions, in which case LinkedList is a good choice. Consider an extreme example where we repeatedly insert an element at the beginning of a list:

Java code
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 (Newarraylist ()));
System.out.println ("LinkedList Time:" +timelist (Newlinkedlist ()));
}
}
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:

Java code
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

5. When inserting data, linkedlist performance is significantly better than ArrayList if the data is inserted in the front segment of the collection (approximately 1/10 of the aggregate capacity), but!!!! When inserting large amounts of data in the middle or even back of a collection, ArrayList's performance is far superior to LinkedList, so the only advantage of LinkedList compared to ArrayList is the insertion of data from the previous segment of the collection.

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 it is an insert or delete operation for another specified location, it is best to select LinkedList.

List

1, list is an interface, can not be instantiated, need to instantiate a ArrayList or LinkedList

List myList = new ArrayList ();

2. You can add any object in the list, including the new class that you defined.

3. Use Mylist.add (any object); You can add it.

4, the value of the time Mylist.get (index), the value is an object, the use of the type conversion required.

5. The iterator iterator can be used to iterate over the elements in the list. The objects in the list collection are emitted in a certain order, and the contents can be duplicated.

List interface Implementation class: ArrayList (Implement dynamic Array), Vector (implement dynamic Array), LinkedList (implement linked list), stack (Implementation stack)

ArrayList

1. How to use ArrayList

The simplest example:

ArrayList List = new ArrayList ();

for (int i=0;i<10;i++)//Add 10 int elements to the array

List.add (i);

//.. Program to do some processing

List.removeat (5);//Remove the 6th element

for (int i=0;i<3;i++)//Add 3 more elements

List.add (I+20);

Int32[] values = (int32[]) List.toarray (typeof (Int32));//Returns an array containing the ArrayList

This is a simple example, although it does not contain all the methods of ArrayList, but it can reflect the most common usage of ArrayList.

2. ArrayList important methods and properties

(1) Constructors

The ArrayList provides three constructors:

public ArrayList ();

The default constructor, which initializes the inner array with the default (16) Size

Public ArrayList (ICollection);

Constructs a ICollection object and adds the elements of the collection to the ArrayList

public ArrayList (int);

Initializes the inner array with the specified size

(2) IsSynchronized properties and Arraylist.synchronized methods

The IsSynchronized property indicates whether the current ArrayList instance supports thread synchronization, while the Arraylist.synchronized static method returns the encapsulation of a ArrayList thread synchronization.

If you are using an instance of non-thread synchronization, you need to manually call lock to maintain thread synchronization when multithreaded access, for example:

ArrayList list = new ArrayList ();

//...

Lock (list. SyncRoot)//When ArrayList is a non-threaded wrapper, the SyncRoot property is itself, but in order to satisfy the SyncRoot definition of ICollection, the SyncRoot is used to maintain the normative nature of the source code.

{

List. Add ("Add a Item");

}

If you use the instance returned by the Arraylist.synchronized method, then you do not have to worry about thread synchronization, the instance itself is thread-safe, in fact, ArrayList internal implementation of a guaranteed thread synchronization internal class, Arraylist.synchronized returned is this Instance of a class, each of which uses the lock keyword to ensure thread synchronization.

****

However, using this method (arraylist.synchronized) does not guarantee the synchronization of enumerations, for example, when one thread is deleting or adding a collection item and another thread is enumerating at the same time, the enumeration throws an exception. So, at the time of enumeration, you must explicitly use SyncRoot to lock the collection.

Hashtable and ArrayList are similar in terms of how thread safety is used.

****

(3) The Count property and the Capacity property

The Count property is the number of elements currently contained in the ArrayList, and this property is read-only.

The capacity property is the maximum number that can be contained by the current ArrayList, which is set manually, but throws an exception when set to less than the count value.

(4) Add, AddRange, Remove, RemoveAt, RemoveRange, Insert, Insertrange

These methods are more similar

The Add method adds an element to the end of the current list

The AddRange method is used to add a batch of elements to the end of the current list

The Remove method is used to delete an element that is removed by a reference to the element itself

The RemoveAt method is used to delete an element by using the index value to remove

RemoveRange is used to delete a batch of elements by specifying the starting index and the number of deletions to delete

Inserts are used to add an element to the specified position, and the elements following the list move backward in turn

Insertrange is used to add a batch of elements starting at the specified position, and the elements behind the list move backwards

In addition, there are several similar methods:

The clear method is used to clear all existing elements

The Contains method is used to find an object that is not in the list

The rest of me is not a liability, you can view the MSDN, above the more careful

(5) Trimsize method

This method is used to pin the ArrayList to the actual element size, and when the dynamic array element is determined not to be added, this method can be called to free up free memory.

(6) ToArray method

This method copy the elements of ArrayList into a new array.

3. ArrayList and Array conversion

Example 1:

ArrayList List = new ArrayList ();

List.add (1);

List.add (2);

List.add (3);

Int32[] values = (int32[]) List.toarray (typeof (Int32));

Example 2:

ArrayList List = new ArrayList ();

List.add (1);

List.add (2);

List.add (3);

Int32[] values = new Int32[list.count];

List.copyto (values);

Two methods for converting from ArrayList to arrays are described above

Example 3:

ArrayList List = new ArrayList ();

List.add ("string");

List.add (1);

Add different types of elements to the array

Object[] Values =list.toarray (typeof (object)); That's right

String[] values = (string[]) List.toarray (typeof (String)); Error

Arrays are different because they can be converted to an object array, so it is not an error to add elements of various types to the ArrayList, but when calling the ArrayList method, either pass the type or object type that all elements can be correctly transformed, Otherwise, an exception that cannot be transformed will be thrown.

Linkedlis

The LinkedList class extends abstractsequentiallist and executes the list interface. It provides a list of linked data structures. It has the following two constructors, which are described below

–linkedlist ()

–linkedlist (Collection c)

– The first constructor establishes an empty list of links.

– The second constructor establishes a list of links that are initialized by the elements in class set C.

Some methods of the LinkedList class public Boolean Add (object element) adds a new node object to the end of the list element

public void Add (int index,object element) adds a new node object to the end of the specified position in the linked list element

public void AddFirst (object element) adds a node object element to the table header of the linked list

public void AddLast (object element) adds a node object element to the end of the list

public void Clear () Deletes all node objects of the linked list

public object Remove (int index) deletes the node object at the specified position

The public boolean Remove object element removes the first occurrence of the node objects element

Public Obiect Removefirst () deletes the first node object and returns the Node object.

public Object Removelast () deletes the last node object

public object get (int index) Gets the node object at the specified position in the linked list

public Object GetFirst () Gets the first node object in a linked list

public Object GetLast () Gets the last node object in the list

public int IndexOf (object element) returns the node object element, where it first appears in the linked list, or 1 if no node in the list is present.

public int LastIndexOf (object element) returns the node object element, the last occurrence in the linked list, or 1 if there is no such node in the linked list

The public object Set (int index, objectelement) replaces the node object at the specified position with the node object element and returns the node object at the previous position in the linked list

public int size () returns the length of the list, that is, the number of nodes

Public Boolean contains (object element) to determine if the list node object contains an element

The LinkedList is implemented using a bidirectional circular chain list. Use LinkedList to implement stacks (stack), queue, and bidirectional queues (double-ended queue).

Vector

ArrayList will be faster than vector, he is non-synchronous, if the design involves multi-threading, or vector better
Import java.util.*;

/**
* Demonstrates the use of vectors. including the creation of vectors, adding elements to vectors, removing elements from vectors,
* Count the number of elements in the vector and traverse the elements in the vector.
*/

public class vectordemo{
public static void Main (string[] args) {

Creation of vectors
Create using the construction method of the vector
Vector v = new vector (4);

Adding elements to the vector
Adding elements directly using the Add method
V.add ("Test0");
V.add ("Test1");
V.add ("Test0");
V.add ("Test2");
V.add ("Test2");

Remove an element from the vector
V.remove ("Test0"); Delete the element of the specified content
V.remove (0); Delete an element by index number

Get the number of elements already in the vector
int size = V.size ();
SYSTEM.OUT.PRINTLN ("Size:" + size);

//Traverse elements in Vector
for (int i = 0;i < V.size (); i++) {
System.out.println (V.get (i));
}
}
}
-------------the
Vector class provides the ability to implement a growing array, and as more elements are added to it, the array becomes larger. After you delete some elements, the array becomes smaller. The
Vector has three constructors,
the public vector (int initialcapacity,int capacityincrement) the public vector (int initialcapacit Y) the Publicvector () Vector runtime creates an initial storage capacity of initialcapacity, which is the incremental growth defined by the capacityincrement variable. The initial storage capacity and capacityincrement can be defined in the vector's constructor. The second constructor creates only the initial storage capacity.   The third constructor does not specify either the initial storage capacity or the capacityincrement. The vector class provides access methods that support similar array operations and operations related to vector size. An array-like operation allows the addition, deletion, and insertion of elements in the vector.   They also allow you to test the contents of the vector and retrieve the specified elements, and the size-dependent operations allow you to determine the size of the bytes and the number of elements in the vector. Now for the frequently used pairs of vectors, delete, interpolation function Example Description:
AddElement (Object obj) to add the component to the end of the vector, while the size plus 1, the vector capacity is larger than the previous 1
Insertelementat (object obj, int in   DEX) Adds the component to the index at which it was set, then moves backwards by 1 units
Setelementat (Object obj, int index) adds the component to the index, where the contents are replaced.   Removeelement (Object obj) removes the contents of this component from the vector.   Removeallelements () Moves all the components in the vector to a vector size of 0.  

Synchronization is a big problem, especially in multi-threading, and processes, so when we operate on an array at the same time in multi-threading, it is a good choice to support a vector that is synchronized, typically when multiple elements need to exist in a collection.
Java.util class Vector<e>
Boolean Add (E o)
Appends the specified element to the end of this vector.
void Add (int index, E Element)
Inserts the specified element at the specified position in this vector.
Boolean AddAll (collection<? extends e> c)
Appends all the elements in the specified Collection to the end of this vector, appending the elements in the order returned by the iterator for the specified collection.
Boolean addall (int index, COLLECTION&LT;? extends e> c)
Inserts all the elements in the specified Collection into this vector at the specified location.
void AddElement (E obj)
Adds the specified component to the end of this vector, increasing its size by 1.
int capacity ()
Returns the current capacity of this vector.
void Clear ()
Removes all elements from this vector.
Object Clone ()
Returns a copy of the vector.
Boolean contains (Object elem)
Tests whether the specified object is a component in this vector.
Boolean containsall (collection<?> c)
Returns true if this vector contains all the elements in the specified Collection.
void Copyinto (object[] anarray)
Copies the component of this vector to the specified array.
E elementat (int index)
Returns the component at the specified index.
Enumeration<e> elements ()
Returns an enumeration of the components of this vector.
void ensurecapacity (int mincapacity)
Increase the capacity of this vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity parameter.
Boolean equals (Object O)
Compares the equality of the specified object to this vector.
E firstelement ()
Returns the first component of this vector (the item at index 0).
E get (int index)
Returns the element at the specified position in the vector.
int Hashcode ()
Returns the hash code value for this vector.
int indexOf (Object elem)
Searches for the first occurrence of a given parameter, using the Equals method to test for equality.
int indexOf (Object elem, int index)
Searches for the first occurrence of a given parameter, starts the search at index, and tests its equality using the Equals method.
void Insertelementat (E obj, int index)
Inserts the specified object as a component in this vector at the specified index.
Boolean IsEmpty ()
Tests whether this vector does not contain components.
E lastelement ()
Returns the last component of this vector.
int lastIndexOf (Object elem)
Returns the index of the last occurrence of the specified object in this vector.
int lastIndexOf (Object elem, int index)
Searches backwards for the specified object, starts the search at the specified index, and returns an index.
E Remove (int index)
Removes the element at the specified position in this vector.
Boolean remove (Object o)
Removes the first occurrence of the specified element in this vector, and if the vector does not contain the element, the element remains unchanged.
Boolean RemoveAll (collection<?> c)
Removes all elements contained in the specified Collection from this vector.
void Removeallelements ()
Removes all components from this vector and sets their size to zero.
Boolean removeelement (Object obj)
Removes the first (least indexed) occurrence of a variable from this vector.
void Removeelementat (int index)
Deletes the component at the specified index.
protected void RemoveRange (int fromIndex, int toindex)
Removes all elements whose indexes are between fromIndex (inclusive) and Toindex (not included) from this list.
Boolean retainall (collection<?> c)
Only the elements contained in the specified Collection are preserved in this vector.
e Set (int index, e Element)
Replaces the element at the specified position in this vector with the specified element.
void Setelementat (E obj, int index)
Sets this vector to the specified object at the component at index.
void setSize (int newSize)
Sets the size of this vector.
int size ()
Returns the number of components in this vector.
list<e> sublist (int fromIndex, int toindex)
Returns a partial view of this List, with elements ranging from fromIndex (including) to Toindex (not included).
Object[] ToArray ()
Returns an array that contains all the elements in the vector that are stored in the correct order.
<T> t[]
ToArray (t[] a)
Returns an array that contains all the elements in the vector in the correct order; The run-time type of the returned array is the type of the specified array.
String toString ()
Returns a string representation of this vector that contains a string representation of each element.
void TrimToSize ()
Fine-tune the capacity of this vector so that it is equal to the current size of the vector.

ArrayList LinkedList Vector

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.