zoukankan      html  css  js  c++  java
  • LinkedList源码分析

    LinkedList源码分析

    LinkedList的成员变量源码

    public class LinkedList<E> extends AbstractSequentialList<E>
     implements List<E>, Deque<E>, Cloneable,
    java.io.Serializable{
      transient int size = 0;
      /**
      *存储第一个节点的引用
      */
      transient Node<E> first;
      /**
      * 存储最后一个节点的引用
      */
      transient Node<E> last;
     
      //......
      //......
    }

    LinkedList的内部类Node类源码

    public class LinkedList<E> extends AbstractSequentialList<E>
     implements List<E>, Deque<E>, Cloneable,
    java.io.Serializable{
      //......
      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的add()方法源码

    public boolean add(E e) {
    linkLast(e);//调用linkLast()方法
    return true;//永远返回true
    }
    void linkLast(E e) {
      final Node<E> l = last;//一个临时变量,存储最后一个节点
      final Node<E> newNode = new Node<>(l, e, null);//创建一个Node对象
    LinkedList的get()方法
    HashSet的源码分析
    HashSet的成员属性及构造方法
      last = newNode;//将新Node对象存储到last
      if (l == null)//如果没有最后一个元素,说明当前是第一个节点
     first = newNode;//将新节点存为第一个节点
      else
     l.next = newNode;//否则不是第一个节点,就赋值到当前的last的next成员
      size++;//总数量 + 1
      modCount++;//
    }

    LinkedList的get()方法

    public E get(int index) {
      checkElementIndex(index);//检查索引的合法性(必须在0-size之间),如果不合法,此方法抛
    出异常
      return node(index).item;
    }
    Node<E> node(int index) {//此方法接收一个索引,返回一个Node
        // assert isElementIndex(index);
        if (index < (size >> 1)) {//判断要查找的index是否小于size / 2,二分法查找
          Node<E> x = first;// x = 第一个节点——从前往后找
          for (int i = 0; i < index; i++)//从0开始,条件:i < index,此循环只控制次
    数
            x = x.next;//每次 x = 当前节点.next;
          return x;//循环完毕,x就是index索引的节点。
       } else {
          Node<E> x = last;// x = 最后一个节点——从后往前找
          for (int i = size - 1; i > index; i--)//从最后位置开始,条件:i > index
            x = x.prev;//每次 x = 当前节点.prev;
          return x;//循环完毕,x就是index索引的节点
       }
     }
  • 相关阅读:
    MyBatis学习总结_17_Mybatis分页插件PageHelper
    MyBatis学习总结_16_Mybatis使用的几个建议
    MyBatis学习总结_15_定制Mybatis自动代码生成的maven插件
    MyBatis学习总结_14_Mybatis使用技巧总结
    MyBatis学习总结_13_Mybatis查询之resultMap和resultType区别
    Git实战之Git创建版本库
    Oracle数据库之日期函数
    Oracle数据库之单表查询
    版本发布后测试人员需要做的工作
    oracle数据库之数据插入、修改和删除
  • 原文地址:https://www.cnblogs.com/chenfx/p/13365369.html
Copyright © 2011-2022 走看看