线性数据结构与节点数据结构增、删、查、修改 优劣介绍

来源:互联网 发布:mac如何压缩图片大小 编辑:程序博客网 时间:2024/05/17 06:58

1、线性数据类有那些?

例如list的子类 Arriylist,Vector,等等底层是由数组进行的无限拓展的容器集合。

 

2、链表的数据类有那些? 

例如:LinkedList,这样的链表 ,底层是有节点对象封装单个数据条目。





首先先从增加功能来看:

Arriylist的增加方法:


    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;         
        return true;
    }

     //增加下标值

    private void ensureCapacityInternal(int minCapacity) {
        modCount++;
        // overflow-conscious code
        //如果这个下标值大于当前元素的总个数,那么就进行扩展

         if (minCapacity - elementData.length > 0)
            grow(minCapacity);
     }

     //这段代码就是进行如果超过当前数据容器的个数,就进行扩大容器  

     private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        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 this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }


      private static int hugeCapacity(int minCapacity) {

    //控制容器的大小。
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }



vector的方法与之类似,只是加了一个同步,防止并发操作。


从上面可以看出来,添加数据 只是在数据的尾部添加数据,但是当数据个数大于底层数组的个数,就会进行扩展容器大小。

linkList的add方法

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #addLast}.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */

    //增加一个特别的元素到这个list的尾部

   public boolean add(E e) {
        linkLast(e);
        return true;
    }


   /**
     * Links e as last element.
     */
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);

      //当增加以后,就以这个增加的元素为最后一个元素,last
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

从上面可以看出来,每次增加一个元素,都相当于增加一个节点,在list的尾部。

从性能上面来说时间上差不多,但是arriylist超过本身数据个数大小范围,就会扩展内容,这时在空间和时间上面会性能相对于linkList较差一些。


接下来看看其他的增加方法:

Arriylist

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);


        ensureCapacityInternal(size + 1);  // Increments modCount!!

        //进行数据项copy,index后面的数据进行往后面移动.
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }

   //检查插入的下标是否有效

    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

linkList

   /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        checkPositionIndex(index);


        if (index == size)

          //这里类似于添加
            linkLast(element);
        else

       
            linkBefore(element, node(index));
    }


   //检查数据项的index 是否正确

    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }


   private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

  

 Node<E> node(int index) {
        // assert isElementIndex(index);
        //查找当前的index的元素

        if (index < (size >> 1)) {  //index的下标很小的时候从前面往后面找
            Node<E> x = first;
            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;
        }
    }




   /**
     * Inserts element e before non-null Node succ.
     */
    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)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }


从上面可以看出,基本的算法思想是找到这个下标的数据   succ,将e的头部地址设置为succ的之前头部的地址,然后将这个数据succ的头 部  地址设置为插入的数据   e。


从时间上来看arriylist  要比linkList的性能要好一些,但从空间上面来看.arriylist进行了一次copy,linkList在空间上比Arriylist要好一些。)


 

增加方法总结:在数据量比较小的时候 用arriylist较好一些,在数据量比较大的时候,linkList要比Arriylist好一些.



--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

查找方法:

Arriylist




    /**
     * Returns the element at the specified position in this list.
     *
     * @param  index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */

    public E get(int index) {

      //检查下标是否越界

        rangeCheck(index);

       //直接返回数组中的index下标的数据
        return elementData(index);

    }



linkList


 

    /**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */



  public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }


 

    /**
     * Returns the (non-null) Node at the specified element index.
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);


        if (index < (size >> 1)) {
            Node<E> x = first;
            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;
        }
    }

从上面可以看出来,按照下标查找数据的时候,ArriyList要比linkList要快一些。



------------------------------------------------------------------------------------------------------------------------------------------

删除方法

ArriyList


 /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     *
     * @param index the index of the element to be removed
     * @return the element that was removed from the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    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; // Let gc do its work


        return oldValue;
    }

  从上面可以看出,删除一个数据,要进行一次数据项的copy.

  ArriYList还有一个根据对象删除的方法

  /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    public boolean remove(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;
    }   


    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; // Let gc do its work
    }


ArriyList的根据对象删除的方法: 首先是找到这个数据项对应的index下标,然后进行数组copy。


 /**
     * Removes all of the elements from this list.  The list will
     * be empty after this call returns.
     */
    public void clear() {
        modCount++;


        // Let gc do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;


        size = 0;
    }

删除全部,是将每个index的数据进行清空,



LinkList相关的删除


  /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If this list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * {@code i} such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns {@code true} if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return {@code true} if this list contained the specified element
     */
    public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }



 /**

  取消x元素与其他元素的关联性
     * Unlinks non-null node x.
     */
    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) {
            first = 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;
    }

//根据下标进行解除关系

 public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }



算法思想:先进行遍历,查找到这个元素,然后进行取消关联.


删除方法总结:

ArriyList根据下标进行删除,在数据量小的情况下,要比LinkList要快些,在数据量大的时候,虽然在遍历查询某个对象的时候,时间上差不多,但是ArriyList要进行一次copy,所以时间上要慢一些.




--------------------------------------------------------------------------------------------------------------

修改方法:

ArriyList

   /**
     * Replaces the element at the specified position in this list with
     * the specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        rangeCheck(index);


        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }



直接根据index找到数据进行赋值.


LinkList


/**
     * Replaces the element at the specified position in this list with the
     * specified element.
     *
     * @param index index of the element to replace
     * @param element element to be stored at the specified position
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

   //查找当前index下标的数据

    Node<E> node(int index) {
        // assert isElementIndex(index);


        if (index < (size >> 1)) {
            Node<E> x = first;
            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;
        }
    }


从上面明显可以看出来ArriyList在进行数据修改的时间上要比LinkList快很多。


总结:

ArriyList 在 修改,查询  上面比LinkList要好很多,在增加 和删除方面,如果是数据量比较小的话,ArriyList还可以用, 如果数据量比较大,LinkList的性能优势就比较明显。


0 0