Java源码解析LinkedList

发布时间:2020-09-23 18:06:40 作者:李灿辉
来源:脚本之家 阅读:170

本文基于jdk1.8进行分析。

LinkedList和ArrayList都是常用的java集合。ArrayList是数组,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;
    }
  }

成员变量如下。它有头节点和尾节点2个指针。

  transient int size = 0;
  /**
   * 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;

下面看一下主要方法。首先是get方法。如下图。链表的get方法效率很低,这一点需要注意,也就是说,我们可以用for循环get(i)的方式去遍历ArrayList,但千万不要这样去遍历Linkedlist。因为Linkedlist进行get时,需要把从头结点或尾节点一个一个的找到第i个元素,效率很低。遍历LinkedList时应该使用foreach方式。

  /**
   * Returns the element at the specified position in this list.
   * @param index index of the element to return
   * @return the element at the specified position in this list
   * @throws IndexOutOfBoundsException {@inheritDoc}
   **/
  public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
  }
  /**
   * Returns the (non-null) Node at the specified element index.
   **/
  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;
    }
  }

下面是add方法,add方法把待添加的元素添加到链表末尾即可。

  /**
   * 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++;
  }

This is the end。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对亿速云的支持。如果你想了解更多相关内容请查看下面相关链接

推荐阅读:
  1. Java源码解析HashMap的tableSizeFor函数
  2. 通过Java源码解析阻塞队列ArrayBlockingQueue

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java linkedlist ava

上一篇:详解vue项目接入微信JSSDK的坑

下一篇:Python with语句上下文管理器两种实现方法分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》