LinkedList 的四种遍历方法

在对比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)

 

  1. 用迭代器遍历
  2. 用列表迭代器遍历
  3. 用size(),get()遍历
  4. 用增强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());
        }

 

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值