Java Collection framework: ArrayList

Source: Internet
Author: User

ArrayList definition
Package java.util; Public  class ArrayList<e> extends abstractlist<e> C9>implements List<E;, randomaccess, cloneable, Java . io. Serializable {    Private Static Final intDefault_capacity =Ten;Private Static FinalObject[] Empty_elementdata = {};PrivateTransient object[] elementdata;Private intSize//remainder omitted}
ArrayList overview

?? ArrayList is implemented as an array, allowing for repetition. Exceeding the limit increases the capacity by 50% (implemented in the Grow () method, as shown below), and each expansion is copied to the new array at the bottom with system.arraycopy (), so it is better to give a pre-estimate of the size of the group. The first time the element is inserted by default, the size of the array is created at ten.

private   void  grow  (int  mincapacity) {//overflow-conscious code  int  oldcapacity = Elementdata.len        Gth int  newcapacity = oldcapacity + (oldcapacity >> 1
     ); if         (Newcapacity-mincapacity < 0 ) newcapacity = mincapacity; if          (Newcapacity-max_array_size > 0 ) newcapacity = hugecapacity (mincapacity); //mincapacity is usually close to size, so the is a win:  Elementdata =    Arrays.copyof (Elementdata, newcapacity); }

?? Accessing elements by array subscript-get (i)/set (i,e) has a high performance, which is the basic advantage of arrays.

public E get(intindex) {        rangeCheck(index);        return elementData(index);    }    public E set(intindex, E element) {        rangeCheck(index);        E oldValue = elementData(index);        elementData[index] = element;        return oldValue;    }

?? the performance of adding elements-add (e) directly at the end of the array is also high, but if you press the subscript insert, delete element-add (i,e), remove (i), remove (e), you use System.arraycopy () to move some of the affected elements, the performance becomes worse , this is a fundamental disadvantage.

  Public BooleanAdd (e e) {ensurecapacityinternal (size +1);//increments modcount!!elementdata[size++] = e;return true; } Public voidAddint Index, E Element) {Rangecheckforadd (Index); Ensurecapacityinternal (size +1);//increments modcount!!System.arraycopy (Elementdata,Index, Elementdata,Index+1, Size-Index); elementdata[Index] = element;    size++; } PublicE Remove (int Index) {Rangecheck (Index);        modcount++; E OldValue = Elementdata (Index);intnummoved = Size-Index-1;if(Nummoved >0) System.arraycopy (Elementdata,Index+1, Elementdata,Index, nummoved); Elementdata[--size] =NULL;//Clear to let GC do it work        returnOldValue; } Public BooleanRemove (Object o) {if(O = =NULL) { for(int Index=0;Index< size;Index++)if(elementdata[Index] ==NULL) {Fastremove (Index);return true; }        }Else{ for(int Index=0;Index< size;Index++)if(O.equals (elementdata[Index]) {Fastremove (Index);return true; }        }return false; }

?? there is a method in ArrayList that TrimToSize () is used to reduce the size of the Elementdata array, which can save memory:

     publicvoidtrimToSize() {        modCount++;        if (size < elementData.length) {            elementData = Arrays.copyOf(elementData, size);        }    }

?? Consider a situation where an application needs a ArrayList to expand to, say, size=10000, after a series of remove operations size=15, the ArrayList size remains within <100 for a long period of time, So it creates a lot of wasted space, it is recommended to explicitly call TrimToSize () This method to optimize memory space.
?? Or the capacity in a ArrayList is fixed, but since each expansion has been expanded by 50%, so there is a certain amount of space wasted, you can call TrimToSize () to eliminate these space waste.
?? non-thread safe , you can call Collections.synchronizedlist (new arraylist<> ());

Use of ArrayList

?? To give a simple example:

         Listlistnew ArrayList<>();        list.add(4);        list.add(2);        list.add(3);        list.add(5);        for(int i:list)        {            System.out.println(i);        }        System.out.println(list);

?? Operation Result:

4235[4235]

?? It is not surprising that ArrayList is stored in the order of insertion , and each insertion is inserted at elementdata[size++].

Use of sublist
list<integer> list = new arraylist<> ();List. Add(4);List. Add(2);List. Add(3);List. Add(5);List. Add(7);List. Add(5);List. Add( One);List. Add( -);List. Add(Ten);List. Add(9);System. out. println(list);list<integer> List2 = List. sublist(3,6);System. out. println(LIST2);List2. Set(2, -);System. out. println("============");System. out. println(list);System. out. println(LIST2);

?? Operation Result:

[4, 2, 3, 5, 7, 5, 11, 14, 10, 9][5, 7, 5]============[4, 2, 3, 5, 7, 50, 11, 14, 10, 9][5, 7, 50]

?? call the Sublist method in ArrayList to generate a new list, internal reference to the original array elementdata, if you change the value in the Sublist, the value in the main list will also change.

randomaccess?!

?? However, the above program has unreasonable! You may be puzzled, please listen to my one by one-way.
?? The above section of the program can be reversed to see Oreach syntax sugar through the compiler processed into a iterator traversal, the details of the foreach syntax can be referred to the Java syntax sugar foreach. As a result of the above program anti-compilation has 100+ line, too much is not listed. As long as you know the truth: foreach for the collection framework, the compilation is parsed into a iterator traversal.
?? So what's wrong with that? The collection frame impression is not the hmm that iterates with the iterator?
?? Note that the special thing about ArrayList is that it implements the Randomaccess interface, which is explicitly stated in the JDK randomaccess:

It isRecognized that  theDistinctionbetweenRandom andSequential access isOften fuzzy. For example,someList implementations provide asymptotically linear access Times ifTheyGetHuge but constantAccess Times inchPractice. Such a List implementation should generally implement this interface. As a rule ofThumb, a List implementation should implement this interfaceif, forTypical instances of  the class, this loop: for(int i=0, n=List. Size (); I < n; i++)List.Get(i); runs faster than this loop: for(Iterator i=List. iterator (); I.hasnext (); ) I.next ();

?? This paragraph of English is mainly to illustrate the implementation of the Randomaccess interface of the set framework, the use of iterative traversal is slow, not recommended.
?? A collection of implementations of the randomaccess interfaces are:ArrayList, attributelist, copyonwritearraylist, Rolelist, Roleunresolvedlist, Stack, Vector , etc.
?? So the traversal in the above example should be written like this:

lengthlist.size();        fori=0;i<length;i++)        {            System.out.println(list.get(i));        }

?? In fact, you can add a judgment, let the program general:

if (listinstanceof RandomAccess)        {            for0list.size(); i++)            {            }        }        else        {            Iterator<?list.iterator();            while (iterator.hasNext())            {                iterator.next();            }        }

?? As a result, bloggers personally feel that there is something wrong with the JDK (JDK7): ArrayList's ToString () method is implemented in Abstractcollection:

Public String toString () {iterator<e> it = Iterator ();if(! It.hasnext ())return "[]"; StringBuilder SB =NewStringBuilder (); Sb.Append(' ['); for(;;)            {e E = It.next (); Sb.Append(E = = this?)"(This Collection)": e);if(! It.hasnext ())returnSb.Append('] '). ToString (); Sb.Append(', ').Append("'); }    }

?? There is no judgment randomaccess, the direct use of the iterator traversal, affecting some performance.

The difference between ArrayList and LinkedList
    1. ArrayList is the realization of the data structure based on dynamic array, LinkedList data structure based on the linked list.
    2. For random access get and set,arraylist feel better than LinkedList because LinkedList wants to move the pointer.
    3. Add and remove,linedlist are the dominant for new and deleted operations because ArrayList is moving the data.
The difference between ArrayList and vectors
    1. Vectors and ArrayList are almost identical, the only difference being that the vector is a synchronous class (synchronized), which belongs to the strong synchronization class. Therefore, the cost is larger than the ArrayList, and the visit is slower. Normally, most Java programmers use ArrayList instead of vectors, because synchronization can be controlled entirely by the programmer itself.
    2. Each time the vector expands it requests twice times its size, while the ArrayList is 1.5 times times.
    3. Vector also has a subclass stack.

Resources:
1. "Java Syntax sugar foreach"

Java Collection framework: ArrayList

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.