栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java源码解析LinkedList

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java源码解析LinkedList

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

linkedList和ArrayList都是常用的java集合。ArrayList是数组,linkedlist是链表,是双向链表。它的节点的数据结构如下。

  private static class Node {
    E item;
    Node next;
    Node prev;
    Node(Node prev, E element, Node next) {
      this.item = element;
      this.next = next;
      this.prev = prev;
    }
  }

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

  transient int size = 0;
  
  transient Node first;
  
  transient Node last;

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

  
  public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
  }
  
  Node node(int index) {
    // assert isElementIndex(index);
    if (index < (size >> 1)) {
      Node x = first;
      for (int i = 0; i < index; i++)
 x = x.next;
      return x;
    } else {
      Node x = last;
      for (int i = size - 1; i > index; i--)
 x = x.prev;
      return x;
    }
  }

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

  
  public boolean add(E e) {
    linkLast(e);
    return true;
  }
  
  void linkLast(E e) {
    final Node l = last;
    final Node newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
      first = newNode;
    else
      l.next = newNode;
    size++;
    modCount++;
  }

This is the end。

总结

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/139210.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号