zoukankan      html  css  js  c++  java
  • LinkedList与ArrayList的get(int index)方法区别

    LinkedList与ArrayList的get(int index)方法区别

    首先我们看看源码

    //LinkedList
    public E get(int index) {
            checkElementIndex(index);
            return node(index).item;
        }
    
    private void checkElementIndex(int index) {
            if (!isElementIndex(index))
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    
    private boolean isElementIndex(int index) {
            return index >= 0 && index < size;
        }
    
    
    
    //ArrayList
    public E get(int index) {
            Objects.checkIndex(index, size);
            return elementData(index);
        }
    
    E elementData(int index) {
            return (E) elementData[index];
        }
    
    transient Object[] elementData;
    

    从源码中我们可以看到,ArrayList是在动态维护一个Object类型的elementData数组,使用get()方法获取元素时,相当于在数组中以元素下标获得元素。而LinkedList是在动态维护一个元素类型为Node的链表,当使用get()方法时,只能从头部或尾部开始访问,(通过size来决定开始位置),然后一个个开始遍历直到该方法获取到index的元素(比如说从头开始,用一个count计数,count = 0,每次访问一个元素count就+1,直到count == index时,输出这个元素。或者从尾开始,count = size - 1,边遍历count边减少,然后直到count == index ,输出这个元素)

    因此,LinkedList的get(int index)方法会比ArrayList的get(int index)方法效率低。

  • 相关阅读:
    table表框去掉相邻的间隔
    各种日期格式化返回
    校验金额、大小写字母、大写字母、合法uri、email
    vue js校验金钱、数字
    vue-router 动态添加 路由
    可视化-echarts流向图制作
    HTTP状态码
    二分查找
    编程语言的变量为啥不能是数字开头
    python位运算
  • 原文地址:https://www.cnblogs.com/ZJHqs/p/15026052.html
Copyright © 2011-2022 走看看