记录学习LinkedList源码过程
2018-04-08 19:11
316 查看
Java集合(JDK8) LinkedList篇
首先先看看LinkedList的继承关系
1、添加一个元素
2、在指定的位置插入元素
首先先看看LinkedList的继承关系
1、添加一个元素
/** * 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; //创建一个结点,数据为e,前驱结点为l,后继结点为null final Node<E> newNode = new Node<>(l, e, null); //将新插入的结点作为尾结点 last = newNode; //如果该结点是第一个结点,则作为首结点 if (l == null) first = newNode; //否则作为l的后继结点 else l.next = newNode; size++; //记录下链表结构改变 modCount++; }
2、在指定的位置插入元素
public void add(int index, E element) { //判断index是否合法 checkPositionIndex(index); //如果index刚好等于链表的长度,则将该结点作为尾结点 if (index == size) linkLast(element); else linkBefore(element, node(index)); }
/** * Returns the (non-null) Node at the specified element index. * 找到第index结点 */ Node<E> node(int index) { // assert isElementIndex(index); //如果index是在前半部分,则从头结点往后遍历 if (index < (size >> 1)) { Node<E> x = first; for (int i = 0; i < index; i++) x = x.next; return x; } else { //如果index是在后半部分,则从尾结点往前遍历 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. * 将结点e插入到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++; }
相关文章推荐
- JDK源码学习系列05----LinkedList
- jdk源码学习笔记--LinkedList
- spark2.2.0源码学习过程记录:Day1 Day2
- Java集合源码学习笔记(三)LinkedList分析
- Java记录 -49- LinkedList源码剖析
- spark2.2.0源码学习过程记录:Day7
- spark2.2.0源码学习过程记录:Day3
- java util包学习(6) LinkedLIst 源码分析
- java LinkedList源码阅读记录
- java1.8 常用集合源码学习:LinkedList
- spark2.2.0源码学习过程记录:Day9
- LinkedList<E>源码学习笔记
- Java集合源码学习笔记(五)ArrayList,LinkedList,Vector和Hashtable,HashMap的比较
- spark2.2.0源码学习过程记录:Day10
- spark2.2.0源码学习过程记录:Day4
- eoe:开篇-记录EOE源码学习过程
- 基于JDK1.8的LinkedList源码学习笔记
- 数据结构与算法学习(二)链式存储结构LinkedList源码分析
- spark2.2.0源码学习过程记录:Day5
- spark2.2.0源码学习过程记录:Day6