Add and remove of ArrayList and LinkedList

Source: Internet
Author: User
Tags assert
Add and remove of ArrayList and LinkedList






The major companies in the Java interview will be a number of Java source problems, this series I will be one for you to analyze
Various Java-important source code


ArrayList and LinkedList are 2 classes that are often compared, because they all implement the list class
Essentially, their underlying storage is different.
Private transient object[] elementdata;


This is the underlying storage method for ArrayList, an array of objects
And what is the bottom of the LinkedList?
private static class Node<e> {
        E item;
        Node<e> Next;
        Node<e> prev;


        Node (node<e> prev, E element, node<e> next) {
            This.item = element;
            This.next = Next;
            This.prev = prev;
        }
    


This is the linkedlist of an internal class, but also the way it is stored, in fact, LinkedList storage mode is a two-way linked list
So the difference, in fact, is that the data structure is the difference between the sequential storage structure and the chain type storage structure.
First look at Add, add method
ArrayList:
Public boolean Add (E e) {
        ensurecapacityinternal (size + 1);  Increments modcount!!
        elementdata[size++] = e;
        return true;
    }
public void Add (int index, E element) {
        Rangecheckforadd (index);


        Ensurecapacityinternal (size + 1);  Increments modcount!!
        System.arraycopy (Elementdata, index, Elementdata, index + 1,
                         size-index);
        Elementdata[index] = element;
        size++;
    }


ArrayList overloaded 2 Add methods, all of which call ensurecapacityinternal (size + 1); This method keeps looking at the call and finds that this method actually
is to create a new array of length size+1, and then copy the value of the array now, and if it is add (e e), put E at the end of the copy, if it is
Add (int index, E Element), you need to make a copy again, build index and after the element to move one bit, and then say the element to the index position is complete, add
Here is a copy of the native layer implementation.
LinkedList:
Public boolean Add (e) {
        linklast (e);
        return true;
    }
public void Add (int index, E element) {
        Checkpositionindex (index);


        if (index = = size)
            linklast (element);
        else
            Linkbefore (element, node (index));
    


You can see that Linklast (e) is called when you add to the end;
void Linklast (e e) {
        final node<e> l = last;
        Final node<e> NewNode = new node<> (l, E, null);
        last = NewNode;
        if (L = = null),
            NewNode;
        else
            l.next = NewNode;
        size++;
        modcount++;
    }


It's just a new node and then put it in the end, and if you don't add it to the end, call the node (index) method to find it.
node<e> node (int index) {
        //Assert Iselementindex (index);


        if (Index < (size >> 1)) {
            node<e> x = i;
            for (int i = 0; i < index; i++)
                x = X.next;
            return x;
        } else {
            node<e> x = last;
            for (int i = size-1 i > index; i--)
                x = X.prev;
            return x;
        }
    }


The lookup here has also been optimized to determine whether the node is near or near the end of the head, and then calls the Linkbefore method to insert
void Linkbefore (e E, node<e> succ) {
        //assert succ!= null;
        Final node<e> pred = Succ.prev;
        Final node<e> NewNode = new Node<> (pred, E, succ);
        Succ.prev = NewNode;
        if (pred = = null)-
            newNode;
        else
            pred.next = NewNode;
        size++;
        modcount++;
    }


Look again Delete, remove method
ArrayList:
Public E-Remove (int index) {
        Rangecheck (index);


        modcount++;
        E OldValue = elementdata (index);


        int nummoved = size-index-1;
        if (nummoved > 0)
            system.arraycopy (Elementdata, index+1, Elementdata, index,
                             nummoved);
        Elementdata[--size] = null; Clear to let GC does its work return


        oldValue;
    }
public boolean remove (Object o) {
        if (o = = null) {for
            (int index = 0; index < size; index++)
                if (elemen Tdata[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;
    }


If you want to delete by index, copy (delete the index position element and adjust the position of the following element), and then empty the last element to facilitate GC recovery
modcount++ because Modcount is the number of times this ArrayList object was modified
If you want to delete it by element, you actually find the index and then call Fastremove ()
private void Fastremove (int index) {
        modcount++;
        int nummoved = size-index-1;
        if (nummoved > 0)
            system.arraycopy (Elementdata, index+1, Elementdata, index,
                             nummoved);
        Elementdata[--size] = null; Clear to let GC does its work
    }


This method is essentially the same as the deletion of the index, except that the bounds of the index are not checked, because this is the search
LinkedList:
Public E-Remove () {return
        removefirst ();
    }
Public E-Remove (int index) {
        checkelementindex (index);
        Return unlink (node (index));
Public boolean-Remove (Object o) {
        if (o = = null) {for
            (node<e> x = i x!= null; x = x.next) {
                if ( X.item = = null) {
                    unlink (x);
                    return true;
                }
            }
        else {for
            (node<e> x = i x!= null; x = x.next) {
                if (o.equals (X.item)) {
                    unlink (x);
                    return true;
                }
            }
        return false;
    }


If it's a direct deletion, call the Removefirst method
Public E Removefirst () {
        final node<e> f = i;
        if (f = = null)
            throw new Nosuchelementexception ();
        Return Unlinkfirst (f);
    }




LinkedList default is to delete the first element
If it is deleted by index, first use node () to find this element, as described earlier, and then call the unlink () method,
E unlink (node<e> x) {
        //assert x!= null;
        Final E element = X.item;
        Final node<e> next = X.next;
        Final node<e> prev = X.prev;


        if (prev = = null) {i
            = next;
        } else {
            prev.next = next;
            X.prev = null;
        }


        if (next = = null) {Last
            = prev;
        } else {
            next.prev = prev;
            X.next = null;
        }


        X.item = null;
        size--;
        modcount++;
        return element;
    }


If you are deleting by element, find that element first, and then call the unlink () method


Summary: 1. Overall look at the add and remove methods of ArrayList and LinkedList, LinkedList to be simpler and more efficient, cause
is because the storage structure is different
2. There is also the discovery of a property we have not seen Modcount, record the number of changes, this attribute what is the use of it, the back slowly to tell us
3. Yes, add, look at the inheritance relationship, will find that ArrayList is inherited abstractlist,abstractlist to realize the list, and
LinkedList is the direct implementation of the list, so LinkedList can be said to be ArrayList's uncle


The next article will detail the query and modification of ArrayList and LinkedList

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.