zoukankan      html  css  js  c++  java
  • 集合框架(六)

    LinkedList

    LinkedList实现了Deque(双向的Queue)接口,和ArrayList和Vector相比,LinkedList的实现方式完全不同。ArrayList和Vector底层都是以数组实现的。而LinkedList是利用对象本身来存储对象,借助记录前一个对象和后一个对象的引用完成对所有对象的遍历。其中有一个存储对象的内部类Node<>,其实现方式如下:
    
    private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;
    
        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }
    
    LinkedList使用Node类代替了数组,根据自身存储的prev和next索引逐个遍历所有对象。因此不适合随机查找,随机查找的get(int)方法实现如下:
    
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }
    
    
    Node<E> node(int index) {
        // assert isElementIndex(index);
    
        if (index < (size >> 1)) {
            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;
        }
    }
    
    可见每次随机查找都要逐一遍历。因此,随机访问元素使用ArrayList要比LinkedList要快很多。
    
    再看看LinkedList的add(E)方法:
    
    public boolean add(E e) {
        linkLast(e);
        return true;
    }
    
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }
    
    LinkedList每次添加元素都要创建Node对象,而ArrayList仅仅使用数组。
  • 相关阅读:
    机器学习【九】数据表达与特征工程
    机器学习【八】数据预处理、降维、特征提取及聚类
    机器学习【七】神经网络
    机器学习【六】支持向量机SVM——专治线性不可分
    机器学习【五】随机森林
    机器学习【四】决策树
    单片机简介 & 点亮LED & 流水灯 & 电路基础
    PHP表单
    机器学习【三】朴素贝叶斯
    PHP 【六】
  • 原文地址:https://www.cnblogs.com/realsoul/p/5751248.html
Copyright © 2011-2022 走看看