在对比ArrayList和LinkedList的get(),add(),remove()三个方法的效率实验(百万数量级)中发现:
使用普通for循环去getLinkedList里的元素的时候,从头开始get(index)效率十分低下,故研究迭代LinkedList的各种方法。方法如下(参考:https://blog.csdn.net/The_Best_Hacker/article/details/81368079)
这里先贴上LinkedList的get,remove方法底层实现:
get:
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
return entry(index).element;
}
private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}
remove:
/**
* Removes the element at the specified position in this list. Shifts any
* subsequent elements to the left (subtracts one from their indices).
* Returns the element that was removed from the list.
*
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
return remove(entry(index));
}
private E remove(Entry<E> e) {
if (e == header)
throw new NoSuchElementException();
E result = e.element;
e.previous.next = e.next;
e.next.previous = e.previous;
e.next = e.previous = null;
e.element = null;
size--;
modCount++;
return result;
}
可以发现,get和remove每次都会从头或者从最后开始遍历找到相应index的element,所以会把不需要的item遍历一遍,故随着item数量增加,在简单的for循环中效率愈发低下。时间复杂度:(1 + 0.5N) * 0.5N =O(N^2)
- 用迭代器遍历
- 用列表迭代器遍历
- 用size(),get()遍历
- 用增强for遍历
1.用迭代器遍历
Iterator iterator=students.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
2.用列表迭代器遍历
ListIterator<Student> listIterator=students.listIterator();
while(listIterator.hasNext()){
System.out.println(listIterator.next());
}
3.用size(),get()遍历
for(int i=0;i<students.size();i++){
System.out.println(students.get(i));
}
4.增强for遍历
for(Student str:students){
System.out.println(str.getName()+"-->"+str.getAge());
}