描述
LinkedList应该也是开发中比较常用的数据结构了,其基于链表数据结构实现,添加和删除效率相对比较高,而随机访问效率偏低
特点
1.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;
}
}
可以看到其有数据,上一个节点和下一个节点,所以其是双向的
而通过查看add源码(add->linkLast)
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++;
}
我们可以看到next的节点为null,所以LinkedList是双向不循环链表
2.添加和删除的效率相对比较高
直接添加的函数在上面已经看到了,其直接修改几个节点地址即可做到添加操作
随机添加的函数如下
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));//node()为根据索引查找的函数,稍后再看
}
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
可以看到,随机添加只是查找到对应索引的节点对象,然后通过修改地址指向来添加到指定位置的
删除的代码:
removeLast->unlinkLast
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
final E element = l.item;
final Node<E> prev = l.prev;
l.item = null;
l.prev = null; // help GC
last = prev;
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
随机删除的代码:(也只是修改地址指向而已)
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;
}
3.随机访问效率较低
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
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;
}
}
通过代码可以发现,每次通过索引来获取数据都需要遍历,如果当前索引靠前就从first向后遍历,否则从last向前遍历,最坏的情况时间复杂度是n/2,所以如果用在RecyclerView.Adapter中就会出现查找的效率问题(频繁遍历)
4.存储数据占用的内存空间更多
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
}
可以看到,每次保存数据都需要将数据包在Node(节点对象)中在保存起来,然后还会有两个对象地址,这样每保存一条数据都会多占用一个Node对象的内存和两个对象地址的内存
5.forEach遍历效率比fori效率更高
使用forEach的话是每次都获取next的节点,而使用fori就是每次都相当于随机获取,显而易见的forEach效率更高
对Kotlin或KMP感兴趣的同学可以进Q群 101786950
如果这篇文章对您有帮助的话
可以扫码请我喝瓶饮料或咖啡(如果对什么比较感兴趣可以在备注里写出来)