Arraylist和Linkedlist的区别

前言

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
个人学习总结使用,如有错误欢迎指出!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值