先上我搜到的大部分结论:LinkedList是用空间不连续的链表实现的,get(index)查询时需要遍历每个元素去查找,时间复杂度O(n),而ArrayList由于是数组实现,get(index)时,直接根据数组的下标返回元素。这个结论其实是错的!
贴上LinkedList根据index获取元素的代码
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
//再看这个node方法
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;
}
}
index < (size >> 1) 会得到index目标元素在链表中的位置,通过与二分之一size的大小比较,来决定是前序遍历还是后序遍历,只遍历了一半的元素,时间复杂度应该为O(n/2)。
=====补充======
LinkedList查找某个元素所在位置时,即index(obj)时,代码如下
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
时间复杂度才是O(n).
总结:LinkedList查询元素有两种方式。根据索引位置查找(时间复杂度O(n/2)根据具体元素查找元素的索引位置(时间复杂度O(n)).