JavaArrayList和LinkedList优缺点

ArrayList和LinkedList优缺点对比

1.ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构。
ArrayList是实现了基于动态数组的数据结构。
LinkedList底层是双向链表的结构。
2.对于随机访问get和set,ArrayList要优于LinkedList,因为LinkedList要移动指针。
3.对于add和remove操作,LinedList有优势,因为ArrayList要移动数据。
4.遍历数据时我们可以使用迭代器遍历数据

public static void main(String[] args) {
        //编程实现证明ArrayList和LinkedList优缺点
        int zs = 0;
        Random r = new Random();
        ArrayList<Integer> alist = new ArrayList<>();
        LinkedList<Integer> llist = new LinkedList<>();

        long ss = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            alist.add(0, r.nextInt(1, 41));
            //由于时间过长,这样可以查看已完成进度
            if (i % 1000 == 0) {
                System.out.println("已完成" + i);
            }
        }
        long ee = System.currentTimeMillis();
        System.out.println(ee - ss);

        ss = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            llist.add(0, r.nextInt(1, 41));
        }
        ee = System.currentTimeMillis();
        System.out.println(ee - ss);

        //ArrayList遍历
        ss = System.currentTimeMillis();
        for (Integer a : alist) {
            zs = a;
        }
        ee = System.currentTimeMillis();
        System.out.println("ArrayList遍历:" + (ee - ss));

        //LinkedList遍历
        ss = System.currentTimeMillis();
        for (Integer a : llist) {
            zs = a;
        }
        ee = System.currentTimeMillis();
        System.out.println("LinkedList遍历:" + (ee - ss));

        //ArrayList遍历使用迭代器
        ss = System.currentTimeMillis();
        Iterator<Integer> ita = alist.listIterator();
        while (ita.hasNext()) {
            zs = ita.next();
        }
        ee = System.currentTimeMillis();
        System.out.println("ArrayList遍历使用迭代器:" + (ee - ss));

        //LinkedList遍历使用迭代器
        ss = System.currentTimeMillis();
        Iterator<Integer> itl = alist.listIterator();
        while (itl.hasNext()) {
            zs = itl.next();
        }
        ee = System.currentTimeMillis();
        System.out.println("LinkedList遍历使用迭代器:" + (ee - ss));
    }

运行结果如图
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值