一、LinkedList具体实现:
我们先看一下,java为我们提供LinkedList是什么样子的:
LinkedList是一种双向链表结构的集合,我们可以通过LinkedList提供的Node类可知,在Node中有三个成员变量(item、next和prev),item存储当前节点的值,next指向当前节点的下一个节点,prev指向当前节点的上一个节点,所以我们说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; } }
LinkedList作为一种链表结构的集合,它的数据维护方式与ArrayList有显著的不同,ArrayList底层是通过数组实现的,ArrayList是在内存中申请的一组连续的内存空间,可以通过下标很容易的找到对应的存储位置,进行数据的维护,LinkedList的添加操作是将新增的数据直接链接到数据链表的尾部。
/** * 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) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); last = newNode; if (l == null) first = newNode; else l.next = newNode; size++; modCount++; }
LinkedList的删除操作,先检查出入的index参数是否符合规定,index这个值必须大于等于0并且小于size,然后调用node()进行元素的查找。
/** * Removes the element at the specified position in this list. Shifts any * subsequent elements to the left (subtracts one from their indices). * Returns the element that was removed from the list. * * @param index the index of the element to be removed * @return the element previously at the specified position * @throws Index