Java ArrayList and LinkedList knowledge points

Source: Internet
Author: User

A ArrayList

1. The ArrayList inside is implemented by an array

/**     * The array buffer into which the elements of the ArrayList is stored.     * The capacity of the ArrayList is the length of this array buffer.     */    private transient object[] elementdata;    /** * The size of the ArrayList (the number of     elements it contains).     *     * @serial * */    private int size;

2. ArrayList can specify the size when initializing, if you know the size, it is best to specify when creating

Public ArrayList (int initialcapacity) {super ();        if (initialcapacity < 0)            throw new IllegalArgumentException ("Illegal capacity:" +                                               initialcapacity); This.elementdata = new object[initialcapacity];    }

3. ArrayList when adding elements, it is necessary to determine whether the array that holds the elements needs to be expanded (the size of the 1/2+1 is the original size)

Public boolean Add (E e) {ensurecapacity (size + 1);  Increments modcount!! elementdata[size++] = E;return true;    } public void ensurecapacity (int mincapacity) {Modcount++;int oldcapacity = elementdata.length;if (Mincapacity > oldcapacity) {    Object olddata[] = elementdata;    int newcapacity = (oldcapacity * 3)/2 + 1;        if (Newcapacity < mincapacity) newcapacity = mincapacity;            Mincapacity is usually close to size, so this is a win:            Elementdata = arrays.copyof (Elementdata, newcapacity);}    }

4. ArrayList add elements at a specified location or remove a specified position element, you need to move more data

public void Add (int index, E element) {if (Index > Size | | Index < 0)    throw new Indexoutofboundsexception ("Index : "+index+", Size: "+size"; ensurecapacity (size+1);  Increments modcount!! System.arraycopy (Elementdata, index, Elementdata, index + 1, size-index); Elementdata[index] = element;size++;    } Public    E Remove (int index) {rangecheck (index); modcount++;  E OldValue = (e) elementdata[index];int nummoved = size-index-1;if (nummoved > 0)    system.arraycopy (Elementdata, Index+1, Elementdata, index,     nummoved); elementdata[--size] = null; Let GC does its workreturn oldValue;    }

two. LinkedList

1. LinkedList is implemented through a linked list, a node is an object that contains the address of the previous node and the next node

Private transient entry<e> Header = new entry<e> (null, NULL, NULL);    private transient int size = 0; private static class Entry<e> {E element; Entry<e> Next; Entry<e> previous; Entry (E element, entry<e> Next, entry<e> previous) {    this.element = element;    This.next = Next;    This.previous = previous;}    }
2. Adding elements is by moving the linked list pointer

Public boolean Add (E e) {Addbefore (E, header);        return true;    } Private entry<e> Addbefore (e E, entry<e> Entry) {entry<e> newEntry = new Entry<e> (e, Entry, Entry. previous); NewEntry.previous.next = newentry;newentry.next.previous = Newentry;size++;modcount++;return newEntry;    }
3. Deleting elements is also by moving the pointer, so theoretically linkedlist is more suitable for adding and deleting operations than ArrayList (no need to determine if expansion is required, no need to move large numbers of elements)

public boolean remove (Object o) {        if (o==null) {            entry<e> e = header.next; E! = header; e = e.next) {
   if (e.element==null) {                    remove (e);                    return true;}}        } else {for            (entry<e> e = Header.next; E! = header; e = e.next) {                if (o.equals (e.element)) {                    remove (e); C11/>return true;}}        }        return false;    } Private E Remove (entry<e> e) {if (E = = header)    throw new Nosuchelementexception ();        E result = E.element;e.previous.next = E.next;e.next.previous = e.previous;        E.next = e.previous = null;        E.element = null;size--;modcount++;        return result;    }
4. Get elements need to traverse linked list, slower than ArrayList

Public E get (int index) {        return Entry (index). element;    } Private entry<e> Entry (int index) {        if (Index < 0 | | index >= size)            throw new Indexoutofboundsexceptio N ("Index:" +index+                                                ", Size:" +size);        entry<e> E = header;        if (Index < (size >> 1)) {//size Right shifts one representation divided by 2, which is actually looking at the previous traversal fast or from the back traversal fast for            (int i = 0; I <= index; i++)                e = e.ne XT;        } else {for            (int i = size; i > Index; i--)                e = e.previous;        }        return e;    }
5. LinkedList iterator that supports forward and backward iterations, removing elements during the iteration. If you are traversing linkedlist, we recommend using iterators, because if you use the Get method, the efficiency of the iterator is not high. (from the source of the Get method can be seen)

 Private class Listitr implements listiterator<e> {private entry<e> lastreturned = Header;private entry<e& Gt next;private int nextindex;private int expectedmodcount = Modcount; LISTITR (int index) {//support starting from the specified position if (Index < 0 | | index > size) throw new Indexoutofboundsexception ("Index:" +in    Dex+ ", Size:" +size); if (Index < (size >> 1)) {next = Header.next;for (nextindex=0; nextindex<index; nextindex++) next = Next.ne    xt    } else {next = Header;for (nextindex=size; nextindex>index; nextindex--) next = next.previous; }}public Boolean Hasnext () {//whether there is the next return nextindex! = size;}    Public E Next () {//Next checkforcomodification ();    if (Nextindex = = size) throw new nosuchelementexception ();    lastreturned = Next;    Next = Next.next;    nextindex++; return lastreturned.element;} public Boolean hasprevious () {//whether there is a previous return nextindex! = 0;} Public E Previous () {//previous if (Nextindex = = 0) throw new nosuchelementexception ();    lastreturned = next = next.previous;    nextindex--;    Checkforcomodification (); return lastreturned.element;} public int Nextindex () {return nextindex;} public int Previousindex () {return nextIndex-1;}            public void Remove () {//delete element checkforcomodification ();            entry<e> lastnext = Lastreturned.next;            try {LinkedList.this.remove (lastreturned);            } catch (Nosuchelementexception e) {throw new illegalstateexception ();            } if (next==lastreturned) next = Lastnext;    elsenextindex--;    lastreturned = header; expectedmodcount++;}    public void Set (E e) {if (lastreturned = = header) throw new IllegalStateException ();    Checkforcomodification (); Lastreturned.element = e;}    public void Add (e e) {checkforcomodification ();    lastreturned = header;    Addbefore (E, next);    nextindex++; expectedmodcount++;} final void Checkforcomodification () {if (Modcount! = EXpectedmodcount) throw new Concurrentmodificationexception ();} }




Java ArrayList and LinkedList knowledge points

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.