java集合--LinkedList源码
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java集合--LinkedList源码,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2341字,纯文字阅读大概需要4分钟。
内容图文
![java集合--LinkedList源码](/upload/InfoBanner/zyjiaocheng/841/51312e4b5b61420dbb9a04714d029a8e.jpg)
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; } }
尾插方法新增节点;只判断了链表是否为空,非空的话向后增加节点,没有数量限制,所以链表的容量可以无线延伸,只受限于内存的大小
/** * 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++; }
remove方法提供了移除链表头结点,尾节点,特定节点,特定index位置的节点;移除首次出现的特定值的节点的方法如下
/** * Removes the first occurrence of the specified element from this list, * if it is present. If this list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index * {@code i} such that * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt> * (if such an element exists). Returns {@code true} if this list * contained the specified element (or equivalently, if this list * changed as a result of the call). * * @param o element to be removed from this list, if present * @return {@code true} if this list contained the specified element */ public boolean remove(Object o) { 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; } /** * Unlinks non-null node x. */ 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.item = null; size--; modCount++; return element; }
从代码中可以看出,null被特殊处理了,也就是说,LinkedList可以储存null;
LinkedList实现了Deque接口,Deque的文档可以参考:https://docs.oracle.com/javase/8/docs/api/java/util/Deque.html
内容总结
以上是互联网集市为您收集整理的java集合--LinkedList源码全部内容,希望文章能够帮你解决java集合--LinkedList源码所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。