arrayList 和 LinkedList 区别

本文通过代码实测比较ArrayList和LinkedList在添加、删除和插入操作上的性能差异。实验结果显示ArrayList在添加元素和删除末尾元素上较快,而LinkedList在插入和删除中间元素上表现更优。分析指出查找操作是影响效率的关键因素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String[] args) {
        long end = 0;
        long start = 0;
        int MAX = 100000;

        // ArrayList新增
        List<Integer> arrayList = new ArrayList();
        start = System.nanoTime();
        for (int x = 0; x < MAX; x++) {
            arrayList.add(x);
        }
        end = System.nanoTime();
        System.out.println("ArrayList新增【10w元素】用时:" + (end - start));

        // LinkedList新增
        List<Integer> linkedList = new LinkedList();
        start = System.nanoTime();
        for (int x = 0; x < MAX; x++) {
            linkedList.add(x);
        }
        end = System.nanoTime();
        System.out.println("LinkedList新增【10w元素】用时:" + (end - start));

        start = System.nanoTime();
        arrayList.add(300);
        end = System.nanoTime();
        System.out.println("ArrayList【插入】元素用时:" + (end - start));


        start = System.nanoTime();
        linkedList.add(300);
        end = System.nanoTime();
        System.out.println("linkedList【插入】元素用时:" + (end - start));



        start = System.nanoTime();
        arrayList.remove(MAX);
        end = System.nanoTime();
        System.out.println("ArrayList删除【末尾】元素用时:" + (end - start));


        start = System.nanoTime();
        ((LinkedList<Integer>) linkedList).removeLast();
        end = System.nanoTime();
        System.out.println("linkedList删除【末尾】元素用时:" + (end - start));


        start = System.nanoTime();
        arrayList.remove(1000);
        end = System.nanoTime();
        System.out.println("ArrayList删除【中间】元素用时:" + (end - start));


        start = System.nanoTime();
        linkedList.remove(1000);
        end = System.nanoTime();
        System.out.println("linkedList删除【中间】元素用时:" + (end - start));

    }

 下图是我跑的运行结果:

结论:ArrayList 底层是数组,查询快、增删慢;LinkedList 底层是链表,查询慢、增删快 ;

但有人说若得出这个结论,你可以让说这个结论的人滚了!!!

分析:无论是添加还是删除,都需要走两个过程:查找到位置,然后添加或者删除; 而查找才是拉开时间效率差距的关键;

这个是别人跑的运行结果,我的代码就是从这人的代码拷贝过来加工的;

ArrayList与LinkedList添加,查找,删除时间比较(问题)_方林-优快云博客

所以我也拿不准这个效率问题;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值