jdk源码学习笔记

编程入门 行业动态 更新时间:2024-10-07 16:26:58

jdk源码<a href=https://www.elefans.com/category/jswz/34/1770117.html style=学习笔记"/>

jdk源码学习笔记

初衷

刚接触java不到2礼拜的小白试图通过阅读jdk的源码来学习java。如有理解或表达不对的地方,欢迎各位大佬指正,谢谢。


1. LinkedList类简介

LinkedList是一个双链表,它也可以被当作堆栈、队列或双端队列进行操作。

LinkedList实现List接口,能对它进行队列操作。LinkedList实现Deque接口,即能将LinkedList当作双端队列使用。

LinkedList实现了Cloneable接口,即覆盖了函数clone(),能克隆。

LinkedList实现java.io.Serializable接口,这意味着LinkedList支持序列化,能通过序列化去传输。

LinkedList是非同步的。

LinkedList类的继承和实现体系如下图所示:

2. Node

既然LinkedList是双链表,那么就先来看下双链表的结点的定义,即Node的定义。Node是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中有两个Node对象,first和last,分别对应双链表的头结点和尾结点。代码如下:

    /*** Pointer to first node.* Invariant: (first == null && last == null) ||*            (first.prev == null && first.item != null)*/transient Node<E> first;/*** Pointer to last node.* Invariant: (first == null && last == null) ||*            (last.next == null && last.item != null)*/transient Node<E> last;

3.构造函数

要实例出LinkedList对象,就会调用到LinkedList的构造函数。LinkedList的构造函数有两个重载版本,一个是无参的,另一个是将另一个collection的元素全部加进来进行构造。代码如下:

    public LinkedList() {}public LinkedList(Collection<? extends E> c) {this();         //构造空的双链表addAll(c);      //copy}

在带参数的构造函数中,调用了addAll方法,这个方法就是用来实现将c的元素copy到现在这个LinkedList实例的功能。下面来看addAll方法,代码如下:

    public boolean addAll(Collection<? extends E> c) {//往链表的末尾加元素return addAll(size, c);}public boolean addAll(int index, Collection<? extends E> c) {//检查index的合法性checkPositionIndex(index);Object[] a = c.toArray();int numNew = a.length;if (numNew == 0)return false;//前驱和后继Node<E> pred, succ;if (index == size) {succ = null;pred = last;} else {succ = node(index);pred = succ.prev;}for (Object o : a) {@SuppressWarnings("unchecked") E e = (E) o;Node<E> newNode = new Node<>(pred, e, null);//如果这个节点的前驱结点是null,那么这个节点应该成为first节点,否则将pred的next指向该节点if (pred == null)first = newNode;elsepred.next = newNode;pred = newNode;}//如果插完所有结点后到了链表末尾那么就链表的last指向该节点,否则就维护链表指针。if (succ == null) {last = pred;} else {pred.next = succ;succ.prev = pred;}size += numNew;modCount++;return true;}

代码中在往链表里插元素时的套路和数据结构课本上的套路一样简单,在这里就不复述了。

4. 增

4.1 public boolean add(E e)

这个方法用于往链表的末尾插入元素,代码如下:

    public boolean add(E e) {linkLast(e);return true;}void linkLast(E e) {final Node<E> l = last;final Node<E> newNode = new Node<>(l, e, null);last = newNode;//如果链表是空的,那么first和last都指向该节点if (l == null)first = newNode;elsel.next = newNode;size++;//和ArrayList一样,用于fast-failmodCount++;}

4.2 public void add(int index, E element)

往指定的位置插入元素,前插,代码如下:

    public void add(int index, E element) {//检查index的合法性[0,size]checkPositionIndex(index);if (index == size)linkLast(element);elselinkBefore(element, node(index));}//succ为index指定的结点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的前驱succ.prev = newNode//前插if (pred == null)first = newNode;elsepred.next = newNode;size++;modCount++;}

在执行linkBefore之前会调用一个叫node的方法,这个方法用于从linkedList中找到给定位置的结点,其实现也很简单,首先会判断给定的index在前一半还是后一半,如果是在前一半那么从first开始往后找,否则就从last开始往前找,代码如下:

    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;}}

4.3 public void addFirst(E e)

把指定的元素插在链表的最前面,代码如下:

    public void addFirst(E e) {linkFirst(e);}private void linkFirst(E e) {final Node<E> f = first;//构造头结点final Node<E> newNode = new Node<>(null, e, f);first = newNode;//如果为空链表,那么first和last都指向该结点if (f == null)last = newNode;elsef.prev = newNode;size++;modCount++;}

4.4 public void addLast(E e)

顾名思义,把指定元素扔在链表的末尾。

    public void addLast(E e) {linkLast(e);}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;elsel.next = newNode;size++;modCount++;}

5. 删

5.1 public boolean remove(Object o)

删除在链表中第一个与o相等的元素,如果链表中没有这个元素,则链表内部什么都不会改变。

    public boolean remove(Object o) {//null也算元素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;}//删除元素的核心代码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结点的所有数据都为null,提醒jvm进行gcx.item = null;size--;modCount++;return element;}

5.2 public E remove(int index)

删除指定位置的结点,其实就是调用node方法拿到结点,然后调用5.1提到的unlink方法。

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

5.3 public E remove()

删除头结点,代码如下:

    public E remove() {return removeFirst();}public E removeFirst() {final Node<E> f = first;//链表是空的还删。。怕不是石乐志if (f == null)throw new NoSuchElementException();return unlinkFirst(f);}private E unlinkFirst(Node<E> f) {// assert f == first && f != null;final E element = f.item;final Node<E> next = f.next;f.item = null;f.next = null; // help GCfirst = next;//next为空的话,现在这个结点被删后就是空链表if (next == null)last = null;elsenext.prev = null;size--;modCount++;return element;}

5.4 public boolean removeFirstOccurrence(Object o)

删除与o相等的第一个结点,无非是调用remove

    public boolean removeFirstOccurrence(Object o) {return remove(o);   //这个本身就是删除与o相等的第一个结点,怕不是怕用户不知道,所以起了个好点的名字}

5.5 public boolean removeLastOccurrence(Object o)

和5.4相反,这个是删除与o相等的最后一个结点。当然套路很简单,看代码吧。

    public boolean removeLastOccurrence(Object o) {if (o == null) {for (Node<E> x = last; x != null; x = x.prev) {if (x.item == null) {unlink(x);return true;}}} else {for (Node<E> x = last; x != null; x = x.prev) {if (o.equals(x.item)) {unlink(x);return true;}}}return false;}

5.5 public void clear()

清空链表,这个方法并不是循环的去调remove或者unlink方法来逐个删除,而是把所有结点的引用都置为null,让gc去收拾烂摊子。

    public void clear() {// Clearing all of the links between nodes is "unnecessary", but:// - helps a generational GC if the discarded nodes inhabit//   more than one generation// - is sure to free memory even if there is a reachable Iteratorfor (Node<E> x = first; x != null; ) {Node<E> next = x.next;x.item = null;x.next = null;x.prev = null;x = next;}first = last = null;size = 0;modCount++;}

6. 改

6.1 public E set(int index, E element)

修改指定位置上的结点的元素,套路很简单,调用node方法拿到结点,然后修改结点的元素。

    public E set(int index, E element) {checkElementIndex(index);Node<E> x = node(index);E oldVal = x.item;x.item = element;return oldVal;}

7. 查

7.1 public E get(int index)

根据指定位置查找结点的元素数据,代码如下:

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

7.2 public int indexOf(Object o)

根据指定的元素来找到相应的位置(第一个相应的位置),代码很简单。

    public int indexOf(Object o) {int index = 0;if (o == null) {for (Node<E> x = first; x != null; x = x.next) {if (x.item == null)return index;index++;}} else {for (Node<E> x = first; x != null; x = x.next) {if (o.equals(x.item))return index;index++;}}return -1;}

7.3 public int lastIndexOf(Object o)

和7.2相反,从后往前找,找到最后一个相应的位置。

    public int lastIndexOf(Object o) {int index = size;if (o == null) {for (Node<E> x = last; x != null; x = x.prev) {index--;if (x.item == null)return index;}} else {for (Node<E> x = last; x != null; x = x.prev) {index--;if (o.equals(x.item))return index;}}return -1;}

8. 单端队列的实现

LinkedList作为一个双链表,但是实现了队列、栈和伪随机访问的功能。吐槽一下:个人感觉这样违背了单一职责原则。。链表就链表嘛,还要整上其他数据结构的功能。。

8.1 获得队头元素

peek方法用来获得队投元素,代码如下:

    public E peek() {final Node<E> f = first;return (f == null) ? null : f.item;}

不过还有个更好一点的方法叫element,这个方法当检测到异常后会抛出异常,代码如下:

    public E element() {return getFirst();}public E getFirst() {final Node<E> f = first;if (f == null)throw new NoSuchElementException();return f.item;}

8.2 获得队尾元素

getLast方法能够获得队尾的元素,代码如下:

    public E getLast() {final Node<E> l = last;if (l == null)throw new NoSuchElementException();return l.item;}

8.3 入队

调用offer方法能够进行入队操作,里面的add方法在前面已经分析过了,这里不再复述。

    public boolean offer(E e) {return add(e);}
    public void addFirst(E e) {linkFirst(e);}public void addLast(E e) {linkLast(e);}

8.4 出队

调用poll方法能够进行出队操作,并返回出队的元素,代码如下:

    public E poll() {final Node<E> f = first;return (f == null) ? null : unlinkFirst(f);}

9. 双端队列的实现

双端队列的实现上无非是和第8节一样,调用前面提到的方法来对链表的数据进行维护,这里不再复述,代码如下:

    //从队头入队public boolean offerFirst(E e) {addFirst(e);return true;}//从队尾入队public boolean offerLast(E e) {addLast(e);return true;}//从队头出队public E peekFirst() {final Node<E> f = first;return (f == null) ? null : f.item;}//从队尾出队public E peekLast() {final Node<E> l = last;return (l == null) ? null : l.item;}

10. 栈的实现

栈的实现上无非是和第9节一样,调用前面提到的方法来对链表的数据进行维护,这里不再复述,代码如下:

    public void push(E e) {addFirst(e);}public E pop() {return removeFirst();}

11. 迭代器

LinkedList的ListItr实现的是ListIterator接口。当外部调用listIterator方法时就会实例出一个ListItr的实例并返回出去。

    public ListIterator<E> listIterator(int index) {checkPositionIndex(index);return new ListItr(index);}//迭代器的定义private class ListItr implements ListIterator<E> {private Node<E> lastReturned;   //当前被访问的结点private Node<E> next;   //还未被访问的结点private int nextIndex;  //当前节点的位置private int expectedModCount = modCount;//fast-failListItr(int index) {// assert isPositionIndex(index);next = (index == size) ? null : node(index);//此时next代表当前节点nextIndex = index;}public boolean hasNext() {return nextIndex < size;}//返回当前节点的引用并往后挪public E next() {//和ArrayList的套路差不多checkForComodification();if (!hasNext())throw new NoSuchElementException();lastReturned = next;next = next.next;nextIndex++;return lastReturned.item;}public boolean hasPrevious() {return nextIndex > 0;}public E previous() {checkForComodification();if (!hasPrevious())throw new NoSuchElementException();lastReturned = next = (next == null) ? last : next.prev;nextIndex--;return lastReturned.item;}public int nextIndex() {return nextIndex;}public int previousIndex() {return nextIndex - 1;}public void remove() {checkForComodification();if (lastReturned == null)throw new IllegalStateException();Node<E> lastNext = lastReturned.next;unlink(lastReturned);//如果next没有更新,那么next直接指向lastnextif (next == lastReturned)next = lastNext;else//如果next已更新,那么nextIndex必定已执行了nextIndex++操作,此时由于删除结点//所以必须执行nextIndex--,才能使nextIndex与next相对应nextIndex--;lastReturned = null;    //不让调用setexpectedModCount++;}public void set(E e) {if (lastReturned == null)throw new IllegalStateException();checkForComodification();lastReturned.item = e;}//前插,add后不能setpublic void add(E e) {checkForComodification();lastReturned = null;    //不让调用setif (next == null)linkLast(e);elselinkBefore(e, next);    //这里因为linkBefore后next还是指向原来的结点,所以next不用往后挪nextIndex++;expectedModCount++;}public void forEachRemaining(Consumer<? super E> action) {Objects.requireNonNull(action);while (modCount == expectedModCount && nextIndex < size) {action.accept(next.item);lastReturned = next;next = next.next;nextIndex++;}checkForComodification();}//当迭代器实例化之后,不允许链表的结构发生改变,除非用迭代器的add和remove方法final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}}

这个迭代器和ArrayList的Itr和ListItr一样都有fast-fail机制,即迭代器实例所指向的LinkedList的实例a,不能通过a调用改变链表结构的方法,否则将抛出异常。也就是说通过a调用改变链表结构的任何方法都使改变结构之前的迭代器失效。

更多推荐

jdk源码学习笔记

本文发布于:2024-02-07 05:53:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1753327.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:学习笔记   源码   jdk

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!