LinkedList源码之内部实现原理(jdk1.8)

本文深入解析了Java中的LinkedList数据结构,重点介绍了其内部基于链表实现导致的高效添加和删除节点的原因。通过源码分析,展示了addFirst、addLast、get和remove等关键方法的工作原理,以及如何通过优化查找策略提升效率。此外,还探讨了unlink方法在帮助垃圾回收方面的作用。
摘要由CSDN通过智能技术生成

LinkedList增删节点效率高,原因是内部基于链表实现,增删节点只需重新设置当前增删节点的左右节点指针即可

LinkedList的结构图:
在这里插入图片描述
LinkedList的内部结构

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{

	//链表的节点个数,默认值0
    transient int size = 0;

   //头节点
    transient Node<E> first;

    //尾节点
    transient Node<E> last;

    //无参构造方法
    public LinkedList() {
    }

	//节点内部类,list内的每个元素就是Node对象
	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;
	        }
	}
}

boolean add(E e)方法的原理:

	/**
     * 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})
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

	/**
     * Links e as last element.
     */
    void linkLast(E e) {
    	//初始化list的时候尾节点last为null,把它赋值给l
        final Node<E> l = last;
        //新节点的上一个节点为l节点的引用,这时newNode的值为:(null,e,null)
        final Node<E> newNode = new Node<>(l, e, null);
        //last指向newNode,这时last的值为:(null,e,null)
        last = newNode;
        //此时l为null
        if (l == null)
        	//当list只有一个节点元素时,List的first和last都指向了newNode,
        	//因为头节点和尾节点都是它,并且头节点尾节点的prev和next都为null
            first = newNode;
        else
        	//当list不止一个list时,在last增加newNode,即在链表末尾追加
            l.next = newNode;
        //容量+1    
        size++;
        //修改数量+1
        modCount++;
    }

void addFirst(E e)方法原理

 	/**
     * Inserts the specified element at the beginning of this list.
     *
     * @param e the element to add
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

	/**
     * Links e as first element.
     * 其实和linkLast()原理一样
     */
    private void linkFirst(E e) {
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }

E get(int index)方法原理

	 /**
     * 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) {
    	//校验索引是否在size范围内,主要看node(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);
		//size>>1是取链表长度一半,这样判断index在哪一个范围内,这样减少了一般遍历次数,提高效率
		//index在前半段范围从头开始遍历
        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        //index后半段范围则从尾端开始遍历    
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

remove(Object o)方法原理

 /**
     * 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) {
            	//遍历链表,匹配到则调用unlink方法
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }
    
   /**
     * 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;
            //个人觉得是:help GC
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值