Java Container & generics: Comparison of ArrayList, LinkedList and vectors

Source: Internet
Author: User
Tags concurrentmodificationexception

Continue on to the container of the article to know the container, the Masons slowly take you into the list of the container commentary. Today Masons want to talk about ArrayList, LinkedList and vector comparisons.

First, List review

Sequence (list), ordered collection, as it is named, is an ordered list of elements. Specifically, lists generally allow e1.equals (E2) elements to E1 and E2, and if the list itself allows null elements, they usually allow multiple null elements. The realization list has: ArrayList, LinkedList, Vector, stack and so on. It is worth mentioning that the vector is in the JDK1.1, and the list in the JDK1.2 when the time comes, we will talk about the difference between ArrayList and vector.

Second, ArrayList vs. Vector

ArrayList is a sequence of resizable array implementations. As the element increases, its size increases dynamically. This class, in iterator or listiterator iterations, calls the Remove and add methods of the container itself to make modifications, throwing concurrentmodificationexception concurrency modification exceptions.

Note that this implementation is not synchronous. if more than one thread accesses a ArrayList instance at the same time, and at least one of the threads modifies the list from the structure, it must remain externally synchronized. (Structural modification refers to any action that adds or removes one or more elements, or explicitly adjusts the size of the underlying array; just setting the value of an element is not a structural modification.) This is typically done by synchronizing the objects that naturally encapsulate the list. If such an object does not exist, you should use the Collections.synchronizedList method to "wrap" the list. This is best done at the time of creation to prevent accidental access to the list in a different step:

        List List = Collections.synchronizedlist (new ArrayList (...));

Below is a demonstration of the relevant ArrayList example.

ArrayList Basic Method Code:

@SuppressWarnings ({"Rawtypes", "unchecked" })     Public Static voidListmethods () {List A1=NewArraylist<string>(); A1.add ("List01"); A1.add ("List03"); A1.add ("List04"); System.out.print ("Original collection: \n\t" +a1+ "\ n"); A1.add (1, "List02"); System.out.print ("Specify the angle label 1 insert: \n\t" +a1+ "\ n"); A1.remove (2); System.out.print ("Specify the corner label 2 Delete: \n\t" +a1+ "\ n"); System.out.print ("Specify Corner 2 query: \n\t" +a1.get (2) + "\ n"); Iterator I1=A1.iterator (); System.out.println ("Query all elements with iterators:");  while(I1.hasnext ()) {System.out.print (I1.next () )+","); }    }

You can see from the console that:

Original set:    [List01, List03, List04] Specify the angle label 1 insert:    [List01, List02, List03, List04] Specify the corner label 2 Delete:    [List01, List02, List04] Specify a corner label 2 query:    List04 query all elements with iterators: list01,list02,list04

In the above we can add (add), delete (remove), get (GET) list elements according to the corner mark. ArrayList provides a iterator iterator to traverse the sequence. It is important to note that the iterator is equivalent to a pointer pointing to the corner label, and the Next () method is equivalent to moving the pointer backward one bit. so remember to use the iterator once in a loop with next ().

The following shows the appearance of the concurrentmodificationexception , and the processing scheme. The Masons demonstrate the appearance of this anomaly with iterator:

@SuppressWarnings ({"Unchecked", "Rawtypes"})  Public Static void  New arraylist<string>= a1.iterator ();  while  = i1.next (); if (Obj.equals ("List02″)") A1.add ("List03″);} System.out.print ("Set: \n\t"+a1+"\ n");}

Run, we can see in the console:

How to solve, first look at this problem. The problem description is clear that, after the iterator is created, the iterator will be thrown whenever the list is modified in any way at any time, unless the list is modified structurally by the remove or add method of the iterator itself ConcurrentModificationException .

So we should modify the code so that we provide the method with the Listiterator iterator:

@SuppressWarnings ({"Unchecked", "Rawtypes" })     Public Static voidListiterator () {List A1=NewArraylist<string>(); A1.add ("List01"); A1.add ("List"); A1.add ("List03"); A1.add ("List04"); Listiterator L1=A1.listiterator ();  while(L1.hasnext ()) {Object obj=L1.next (); if(Obj.equals ("List") ) {l1.remove (); L1.add ("List02"); }} System.out.print ("Collection: \n\t" +a1+ "\ n"); }

Running, we can see:

Collection:    [List01, List02, List03, List04]

This allows us to successfully resolve this concurrency modification exception. Remove the ' List ' element and add a ' List02 ' element.

Vectors are very similar to ArrayList. As early as the JDK1.1, there was no known list interface, and now this class has been improved to implement the list interface. But unlike the new collection, vectors are synchronous . Masons want to say that the vector, in the performance of like query than ArrayList overhead. The following is a basic example of vector:

@SuppressWarnings ({"Unchecked", "Rawtypes" })     Public Static voidVectormethods () {Vector V1=NewVector<string>(); V1.add ("Vector001"); V1.add ("Vector002"); V1.add ("Vector003"); V1.add ("Vector004"); V1.add ("Vector005"); Enumeration E1=v1.elements ();  while(E1.hasmoreelements ()) {Object Object=e1.nextelement ();        System.out.println (object); }    }

There is almost no difference from the method, the same note : The function of this interface and the function of the Iterator interface are duplicated. Additionally, the Iterator interface adds an optional remove operation and uses a shorter method name. The new implementation should prioritize the use of the Iterator interface instead of the enumeration interface.

Third, LinkedList and its performance ratio with ArrayList

LinkedList and ArrayList as the implementation of the list interface, LinkedList is the list interface linked list implementation. A list-based approach makes LinkedList better than ArrayList when inserting and deleting, while random access is less than ArrayList. The LinkedList implements all optional list operations and allows all elements to include NULL. In addition to implementing the list interface, the LinkedList class provides a uniform naming method for the get, remove, and insert elements at the beginning and end of the list. These operations allow the link list to be used as a stack, queue, or double-ended queue .

The method of LinkedList and ArrayList time complexity is summarized as shown.

table, adding Add () refers to the method of adding an element, remove () is the drop (int index) corner label. ArrayList has an O (N) of any exponential time complexity added/removed, but O (1) at the end of the list of operations. An O (n) of the linked list is added/removed for any exponential time complexity, but O (1) the start of the operation end/list.

The Masons verify this conclusion with code:

 Public Static voidTestperbtwnarlandlkl () {ArrayList<Integer> arrayList =NewArraylist<integer>(); LinkedList<Integer> LinkedList =NewLinkedlist<integer>(); //ArrayList Add        LongStartTime =System.nanotime (); LongEndTime; Longduration;  for(inti = 0; I < 100000; i++) {arraylist.add (i); } endTime=System.nanotime (); Duration= EndTime-StartTime; System.out.println ("ArrayList Add:" +duration); //LinkedList AddStartTime =System.nanotime ();  for(inti = 0; I < 100000; i++) {linkedlist.add (i); } endTime=System.nanotime (); Duration= EndTime-StartTime; System.out.println ("LinkedList add:" +duration); //ArrayList GetStartTime =System.nanotime ();  for(inti = 0; I < 10000; i++) {arraylist.get (i); } endTime=System.nanotime (); Duration= EndTime-StartTime; System.out.println ("ArrayList Get:" +duration); //LinkedList GetStartTime =System.nanotime ();  for(inti = 0; I < 10000; i++) {linkedlist.get (i); } endTime=System.nanotime (); Duration= EndTime-StartTime; System.out.println ("LinkedList Get:" +duration); //ArrayList RemoveStartTime =System.nanotime ();  for(inti = 9999; I >=0; i--) {arraylist.remove (i); } endTime=System.nanotime (); Duration= EndTime-StartTime; System.out.println ("ArrayList Remove:" +duration); //LinkedList RemoveStartTime =System.nanotime ();  for(inti = 9999; I >=0; i--) {linkedlist.remove (i); } endTime=System.nanotime (); Duration= EndTime-StartTime; System.out.println ("LinkedList Remove:" +duration); }

The console output is as follows:

ArrayList add:  1690477612015418ArrayList get:  1304593108950741ArrayList Remove:  787388127128145950

In contrast, the performance gap is obvious. LinkedList performance is fast in addition and removal, but in poor performance in Fetch. From the complexity and test results, we should know how to add or remove frequently in the place, choose LinkedList when considering:

1. Random access without a large number of elements

2. Add/Remove Operations

Naturally I use linedlist to implement a data structure-stack. The Masons left a few ways for everyone to linkedlist their own digestion.

 Packagecom.sedion.bysocket.collection;Importjava.util.LinkedList;/*** using LinkedList to implement stack * queue and Stack differences: Queue FIFO, stack advanced out. */ Public classStack<t>{    Privatelinkedlist<t> storage =NewLinkedlist<t>(); /**into the stack*/     Public voidpush (T v) {Storage.addfirst (v); }     /**out of the stack, but not deleted*/     PublicT Peek () {returnStorage.getfirst (); }     /**out of the stack, delete*/     PublicT Pop () {returnStorage.removefirst (); }     /**whether the stack is empty*/     Public Booleanempty () {returnStorage.isempty (); }     /**Output Stack elements*/     PublicString toString () {returnstorage.tostring (); }          Public Static voidMain (string[] args) {Stack stack=NewStack<string>(); Stack.push (A); Stack.push ("B"); Stack.push (C);        System.out.println (Stack.tostring ()); Object obj=Stack.peek (); System.out.println (obj+"--"+stack.tostring ()); Obj=Stack.pop (); System.out.println (obj+"--"+stack.tostring ());    System.out.println (Stack.empty ()); }}
Iv. Summary

Masons are summarized as follows:

Vector and ArrayList

1, vector is thread synchronization, so it is also thread-safe, and ArrayList is thread-asynchronous, is not secure.

2, remember the concurrency modification exception java.util.ConcurrentModificationException, priority to consider ArrayList, unless you are using multithreading required.

Aarraylist and LinkedList
1, for random access get and set,arraylist feel better than linkedlist,linkedlist to move the pointer.
2, in the new and delete operations Add and remove,linedlist more dominant, ArrayList to move the data.
3.
Single data insertion or deletion, ArrayList speed is better than LinkedList. The reason is: LinkedList data structure is three objects, the appropriate size of the group will be faster than the linked list, the direct assignment is over, no longer set the value of the pointer before and after.
If bulk random Insert delete data, LinkedList speed is much better than ArrayList. Because ArrayList each insertion of data, you move the insertion point and all subsequent data.

Reprinted from: http://www.bysocket.com/?p=169

Java Container & generics: Comparison of ArrayList, LinkedList and vectors

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.