首页 > 其他 > 详细

LinkedList底层源码

时间:2021-08-16 10:13:09      阅读:18      评论:0      收藏:0      [点我收藏+]

JDK1.7和1.8 LinkedList的源码是一样的

public class LinkedList<E> {//e是一个反选,具体的类型要在实例化的时候确定
}
transient int size = 0;//集合中元素的数量
?
  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;
      }
  }
  transient Node<E> first;//链表的首节点
  transient Node<E> last;//链表的尾节点
  //空构造器
    public LinkedList() {
  }
  //添加元素操作
    public boolean add(E e) {
      linkLast(e);
      return true;
  }
      void linkLast(E e) {//添加的元素e
      final Node<E> l = last;//将链表中的last节点给l,如果是第一个元素的话,那l位null
      final Node<E> newNode = new Node<>(l, e, null);//将元素封装为一个Node具体的对象,
      last = newNode;//将链表的last节点,指向新的创建对象
      if (l == null)//如果添加的是第一个节点
          first = newNode;//将链表的first指向为新的节点
      else//如果添加的是下一个节点
          l.next = newNode;//将i的下一个指向为新的节点
      size++;//集合中元素数量加1
      modCount++;
       
   
      public int size() {//获取集合中元素数量
      return size;
       
        public E get(int index) {//通过索引获得元素
      checkElementIndex(index);//健壮性可以不看
      return node(index).item;
       
       
        Node<E> node(int index) {
      // assert isElementIndex(index);
?
      if (index < (size >> 1)) {//如果index在链表的前半段,那么从前往后找
          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;
      }
  }
  }
       
       
  }
  }

 

LinkedList底层源码

原文:https://www.cnblogs.com/java5745/p/15145244.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!