LinkedList源码分析
2015-09-10 14:02
369 查看
LinkedList底层实现采用双向循环链表。LinkedList的插入与删除操作都不涉及到元素的移动,改变的只是元素的指向而已。
LinkedList的查找速度是很慢的,因为涉及到元素的逐个获取与比较。
LinkedList与ArrayList的区别,本质上是链表和数组的区别。
查看LinkedList的构造方法
其构造方法内容为空
然后看add方法
查看linkLast(e)
Node其实就是一个双向链表
这样就实现了添加一个元素。
remove方法
LinkedList的查找速度是很慢的,因为涉及到元素的逐个获取与比较。
LinkedList与ArrayList的区别,本质上是链表和数组的区别。
import java.util.LinkedList; import java.util.List; public class Test2 { public static void main(String[] args) { List<String> list = new LinkedList<>(); list.add("a"); } }
查看LinkedList的构造方法
/** * Constructs an empty list. */ public LinkedList() { }
其构造方法内容为空
然后看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; }
查看linkLast(e)
/** * 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++; }
Node其实就是一个双向链表
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; } }
这样就实现了添加一个元素。
remove方法
/** * 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; }
相关文章推荐
- Django学习笔记1
- iOS-判断字符串中是否只含有\n
- linux安装包制作
- pdf转换成txt格式的方法与步骤
- 在arm上搭建flask运行环境
- 使用MsgPack配合Qt应用程序和node.js应用程序的数据传输
- Android style
- framework制作
- gradle安装记录
- Kaldi中的nnet3之数据类型
- SVN学习笔记9 -- SVN Eclipse 插件安装-- 新的旅程
- poj1420 拓扑序
- linux_常用压缩,解压缩命令
- input和textarea设定提示信息和默认值
- javascript语法
- 练习赛
- SES机箱管理知识回顾(一) 之SES标准介绍
- 简析Serializable 和 Parcelable 区别
- 《TCP/IP详细说明》读书笔记(17章)-TCP传输控制协定
- mciSendString用法