LinkedList 元素查找为什么效率慢?

代码示例:

    public static void main(String[] args) {
        LinkedList<String> linkedList =new LinkedList<String>();


        linkedList.add("a");
        linkedList.add("b");
        linkedList.add("c");
        linkedList.add("d");
        linkedList.add("e");


        System.out.println(linkedList);
        System.out.println(linkedList.get(1));    
    }

输出结果:[a, b, c, d, e]
                  b

底层源码:

 public E get(int index) {
                  checkElementIndex(index);
                  return node(index).item;
        }

  Node<E> node(int index) {
        // assert isElementIndex(index);

      //从链表的前段开始查找 

      if (index < (size >> 1)) {   //传入进来的索引的大小,与集合尺寸 size/2的结果进行比较。判断要查找的元素距离首末两端的                                                  //距离
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;              //由于是链表数据结构,所以是不停的进行迭代查找下一个元素,这就是慢的原因
            return x;

//从链表的后面开始查找
        } else {  
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_38214630/article/details/84998586