前言
ArrayList和LinkedList比较
提示:以下是本篇文章正文内容,下面案例可供参考
一、ArrayList和LinkedList的add方法比较
同样是再尾部添加的时候,数量级是300000以下,linkedList速度较快,由于ArrayList的扩容机制,比较占用时间,而linkedList只是new一个节点对象。300000以上时,同样因为是扩容的原因,一次范围较大,此时链表创建对象的时间较大。 按照index位置插入的时候,ArrayList的源码如下public void add(int index, E element) {
this.rangeCheckForAdd(index);
++this.modCount;
int s;
Object[] elementData;
if ((s = this.size) == (elementData = this.elementData).length) {
elementData = this.grow();
}
System.arraycopy(elementData, index, elementData, index + 1, s - index);
elementData[index] = element;
this.size = s + 1;
}
从上面不难看出,数组需要位移一位。
LinkedList源码如下:
public void add(int index, E element) {
this.checkPositionIndex(index);
if (index == this.size) {
this.linkLast(element);
} else {
this.linkBefore(element, this.node(index));
}
}
LinkedList.Node<E> node(int index) {
LinkedList.Node x;
int i;
if (index < this.size >> 1) {
x = this.first;
for(i = 0; i < index; ++i) {
x = x.next;
}
return x;
} else {
x = this.last;
for(i = this.size - 1; i > index; --i) {
x = x.prev;
}
return x;
}
}
linkedList需要遍历将近一半数量的元素。
ArrayList需要移动数据,而linkedlist只是改变指针的指向,此时linkedList快。
删除元素的时候也是类似,linkedList快,不需要位移元素
二、使ArrayList和LinkedList的遍历比较
使用for循环遍历比较,ArrayList根据索引快速查找定位,list.get(i)的方法
public E get(int index) {
Objects.checkIndex(index, this.size);
this.checkForComodification();
return this.root.elementData(this.offset + index);
}
LinkedList遍历list.get(i)
public E get(int index) {
this.checkElementIndex(index);
return this.node(index).item;
}
LinkedList.Node<E> node(int index) {
LinkedList.Node x;
int i;
if (index < this.size >> 1) {
x = this.first;
for(i = 0; i < index; ++i) {
x = x.next;
}
return x;
} else {
x = this.last;
for(i = this.size - 1; i > index; --i) {
x = x.prev;
}
return x;
}
}
由此可见,arraylist使用for循环遍历快,linkedlist的慢
使用iterator迭代器遍历
LinkedList效率比较高这是因为iterator的next(),是顺着链表节点顺序读取数据,所以效率就很高了
总结
参考:https://www.cnblogs.com/cosmos-wong/p/11931275.html
个人学习总结使用,如有错误欢迎指出!