thinking in java (十七) ----- 集合之List总结

List概括

首先回顾一下关系图

  1. Lsit是一个接口,继承与Collection接口,它代表的是有序的队列
  2. AbstractList是一个抽象类,它继承于AbstractCollection,AbstractList实现List接口中除了size(),get(index)之外的函数
  3. AbstractSequentialList是一个抽象类,继承于Abstract。AbstractSequentialList实现了“链表中根据index索引操作链表的全部函数”
  4. ArrayList,LinkedList,Vector,Stack是List的4个实现类

ArrayList是数组队列,相当于是动态数组。他由数组实现,随机访问效率极高,随机插入,删除,尤其是中间部分的地方,效率低,线程不安全

LinkedList是一个双向链表,他可以被当做堆栈队列,双端队列进行操作,LinkedList随机访问效率低,但是随机插入随机删除的效率高,线程不安全

Vector是矢量队列,和ArrayList一样是动态数组。但是是线程安全

Stack是栈,继承与Vector,廷行事先进后出

List使用场景

如果涉及到“栈”“队列”“链表”,应该考虑使用List,具体使用哪个List根据下面的标准来决定

  1. 对于需要快速插入,删除元素,使用LinkedList
  2. 需要快速随机访问,使用ArrayList
  3. 对于单线程 或者多线程,但是List只会被单个线程操作,就应该使用非同步类,如ArrayList,对于多线程环境,且List可能被多个线程操作,就使用同步的的类,如Vector

通过下面的测试程序,我们来验证1,2的结论

public class Main {

    private static final int COUNT = 100000;

    private static LinkedList linkedList = new LinkedList();
    private static ArrayList arrayList = new ArrayList();
    private static Vector vector = new Vector();
    private static Stack stack = new Stack();

    public static void main(String[] args) {
        // 换行符
        System.out.println();
        // 插入
        insertByPosition(stack) ;
        insertByPosition(vector) ;
        insertByPosition(linkedList) ;
        insertByPosition(arrayList) ;

        // 换行符
        System.out.println();
        // 随机读取
        readByPosition(stack);
        readByPosition(vector);
        readByPosition(linkedList);
        readByPosition(arrayList);

        // 换行符
        System.out.println();
        // 删除 
        deleteByPosition(stack);
        deleteByPosition(vector);
        deleteByPosition(linkedList);
        deleteByPosition(arrayList);
    }

    // 获取list的名称
    private static String getListName(List list) {
        if (list instanceof LinkedList) {
            return "LinkedList";
        } else if (list instanceof ArrayList) {
            return "ArrayList";
        } else if (list instanceof Stack) {
            return "Stack";
        } else if (list instanceof Vector) {
            return "Vector";
        } else {
            return "List";
        }
    }

    // 向list的指定位置插入COUNT个元素,并统计时间
    private static void insertByPosition(List list) {
        long startTime = System.currentTimeMillis();

        // 向list的位置0插入COUNT个数
        for (int i=0; i<COUNT; i++)
            list.add(0, i);

        long endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println(getListName(list) + " : insert "+COUNT+" elements into the 1st position use time:" + interval+" ms");
    }

    // 从list的指定位置删除COUNT个元素,并统计时间
    private static void deleteByPosition(List list) {
        long startTime = System.currentTimeMillis();

        // 删除list第一个位置元素
        for (int i=0; i<COUNT; i++)
            list.remove(0);

        long endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println(getListName(list) + " : delete "+COUNT+" elements from the 1st position use time:" + interval+" ms");
    }

    // 根据position,不断从list中读取元素,并统计时间
    private static void readByPosition(List list) {
        long startTime = System.currentTimeMillis();

        // 读取list元素
        for (int i=0; i<COUNT; i++)
            list.get(i);

        long endTime = System.currentTimeMillis();
        long interval = endTime - startTime;
        System.out.println(getListName(list) + " : read "+COUNT+" elements by position use time:" + interval+" ms");
    }
}

结果:
Stack : insert 100000 elements into the 1st position use time:1169 ms
Vector : insert 100000 elements into the 1st position use time:1179 ms
LinkedList : insert 100000 elements into the 1st position use time:7 ms
ArrayList : insert 100000 elements into the 1st position use time:1214 ms

Stack : read 100000 elements by position use time:4 ms
Vector : read 100000 elements by position use time:3 ms
LinkedList : read 100000 elements by position use time:4792 ms
ArrayList : read 100000 elements by position use time:1 ms

Stack : delete 100000 elements from the 1st position use time:1085 ms
Vector : delete 100000 elements from the 1st position use time:1067 ms
LinkedList : delete 100000 elements from the 1st position use time:4 ms
ArrayList : delete 100000 elements from the 1st position use time:1088 ms

  • 我们可以发现

插入十万个元素,LinkedList用时最短

删除十万个元素,LinkedList用时最短

遍历十万个元素,ArrayList和Stack,Vector用时差不多,LinkedList用时最长,

考虑到Vctor还是同步的,Stack又是继承Vector,得出结论:

  1. 对于需要快速插入,删除,应该使用LinkedList
  2. 对于需要快访问元素,应该使用ArrayList
  3. 对于要求线程安全的,在多线程环境下的,应该使用Vector 或者Stack

LinkedList和ArrayList性能差异

我们从源代码中看一下,为什么LinkedList会插入元素很快,而ArrayList中插入元素很慢,下面是LinkedList的add方法源代码:

// 在index前添加节点,且节点的值为element
public void add(int index, E element) {
    addBefore(element, (index==size ? header : entry(index)));
}

// 获取双向链表中指定位置的节点
private Entry<E> entry(int index) {
    if (index < 0 || index >= size)
        throw new IndexOutOfBoundsException("Index: "+index+
                                            ", Size: "+size);
    Entry<E> e = header;
    // 获取index处的节点。
    // 若index < 双向链表长度的1/2,则从前向后查找;
    // 否则,从后向前查找。
    if (index < (size >> 1)) {
        for (int i = 0; i <= index; i++)
            e = e.next;
    } else {
        for (int i = size; i > index; i--)
            e = e.previous;
    }
    return e;
}

// 将节点(节点数据是e)添加到entry节点之前。
private Entry<E> addBefore(E e, Entry<E> entry) {
    // 新建节点newEntry,将newEntry插入到节点e之前;并且设置newEntry的数据是e
    Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
    // 插入newEntry到链表中
    newEntry.previous.next = newEntry;
    newEntry.next.previous = newEntry;

从中,我们可以看出:通过add(int index, E element)向LinkedList插入元素时。先是在双向链表中找到要插入节点的位置index;找到之后再插入一个新节点
双向链表查找index位置的节点时,有一个加速动作若index < 双向链表长度的1/2,则从前向后查找; 否则,从后向前查找

ArrayList源代码

// 将e添加到ArrayList的指定位置
public void add(int index, E element) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);

    ensureCapacity(size+1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
         size - index);
    elementData[index] = element;
    size++;
}

ensureCapacity(size+1) 的作用是“确认ArrayList的容量,若容量不够,则增加容量。
真正耗时的操作是 System.arraycopy(elementData, index, elementData, index + 1, size - index);System.arraycopy(elementData, index, elementData, index + 1, size - index); 会移动index之后所有元素这就意味着,ArrayList的add(int index, E element)函数,会引起index之后所有元素的改变!

通过上面的分析,我们就能理解为什么LinkedList中插入元素很快,而ArrayList中插入元素很慢。
“删除元素”与“插入元素”的原理类似

// 返回LinkedList指定位置的元素
public E get(int index) {
    return entry(index).element;
}

// 获取双向链表中指定位置的节点
private Entry<E> entry(int index) {
    if (index < 0 || index >= size)
        throw new IndexOutOfBoundsException("Index: "+index+
                                            ", Size: "+size);
    Entry<E> e = header;
    // 获取index处的节点。
    // 若index < 双向链表长度的1/2,则从前先后查找;
    // 否则,从后向前查找。
    if (index < (size >> 1)) {
        for (int i = 0; i <= index; i++)
            e = e.next;
    } else {
        for (int i = size; i > index; i--)
            e = e.previous;
    }
    return e;
}

接下来,我们看看 “为什么LinkedList中随机访问很慢,而ArrayList中随机访问很快”

先看看LinkedList随机访问的代码

// 返回LinkedList指定位置的元素
public E get(int index) {
    return entry(index).element;
}

// 获取双向链表中指定位置的节点
private Entry<E> entry(int index) {
    if (index < 0 || index >= size)
        throw new IndexOutOfBoundsException("Index: "+index+
                                            ", Size: "+size);
    Entry<E> e = header;
    // 获取index处的节点。
    // 若index < 双向链表长度的1/2,则从前先后查找;
    // 否则,从后向前查找。
    if (index < (size >> 1)) {
        for (int i = 0; i <= index; i++)
            e = e.next;
    } else {
        for (int i = size; i > index; i--)
            e = e.previous;
    }
    return e;
}

从中,我们可以看出:通过get(int index)获取LinkedList第index个元素时先是在双向链表中找到要index位置的元素;找到之后再返回。
双向链表查找index位置的节点时,有一个加速动作若index < 双向链表长度的1/2,则从前向后查找; 否则,从后向前查找。

下面看看ArrayList随机访问的代码 

// 获取index位置的元素值
public E get(int index) {
    RangeCheck(index);

    return (E) elementData[index];
}

private void RangeCheck(int index) {
    if (index >= size)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);
}

从中,我们可以看出:通过get(int index)获取ArrayList第index个元素时。直接返回数组中index位置的元素,而不需要像LinkedList一样进行查找。

Vctor和ArrayList比较

  • 都是继承List

他们都是继承自AbstractList,实现List接口。类的定义如下

// ArrayList的定义
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

// Vector的定义
public class Vector<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable {}
  • 都实现了RandomAccess和Cloneable接口

说明支持克隆和随机快速访问

  • 都是通过数组实现

ArrayList定义数组elementData存放元素

// 保存ArrayList中数据的数组
private transient Object[] elementData;

Vctor也定义数组elementData存放元素

// 保存Vector中数据的数组
protected Object[] elementData;

从上面代码可以看出,ArrayList使用 transient 修饰了 elementData 数组。这保证系统序列化ArrayList对象时不会直接序列号elementData数组,而是通过ArrayList提高的writeObject、readObject方法来实现定制序列化;但对于Vector而言,它没有使用transient修饰elementData数组,而且Vector只提供了一个writeObject方法,并未完全实现定制序列化。 

  • 初始容量都是10

默认构造函数

// ArrayList构造函数。默认容量是10。
public ArrayList() {
    this(10);
}
————————————————————————————————
// Vector构造函数。默认容量是10。
public Vector() {
    this(10);
} 
  • 都支持迭代器遍历

都继承自AbstractList,实现了Iterator迭代器

  • 不同之处

  • 线程安全性

ArrayList非线程安全的,Vctor线程安全,所有方法都是synchronize。

ArrayList适应于单线程,Vector适用于多线程

  • 序列化支持

 ArrayList的底层数组支持序列化,而Vector的底层数组不支持;上面代码也有写

  • 构造函数个数

ArrayList构造函数

// 默认构造函数
ArrayList()

// capacity是ArrayList的默认容量大小。当由于增加数据导致容量不足时,容量会添加上一次容量大小的一半。
ArrayList(int capacity)

// 创建一个包含collection的ArrayList
ArrayList(Collection<? extends E> collection)

 Vector构造:

// 默认构造函数
Vector()

// capacity是Vector的默认容量大小。当由于增加数据导致容量增加时,每次容量会增加一倍。
Vector(int capacity)

// 创建一个包含collection的Vector
Vector(Collection<? extends E> collection)

// capacity是Vector的默认容量大小,capacityIncrement是每次Vector容量增加时的增量值。
Vector(int capacity, int capacityIncrement)
  • 容量增加方式

逐个添加元素时,若ArrayList容量不足时,“新的容量”=“(原始容量x3)/2 + 1”。(1.5倍)
   而Vector的容量增长与“增长系数有关”,若指定了“增长系数”,且“增长系数有效(即,大于0)”;那么,每次容量不足时,“新的容量”=“原始容量+增长系数”。若增长系数无效(即,小于/等于0),则“新的容量”=“原始容量 x 2”。

ArrayList中容量增长的主要函数如下:

public void ensureCapacity(int minCapacity) {
    // 将“修改统计数”+1
    modCount++;
    int oldCapacity = elementData.length;
    // 若当前容量不足以容纳当前的元素个数,设置 新的容量=“(原始容量x3)/2 + 1”
    if (minCapacity > oldCapacity) {
        Object oldData[] = elementData;
        int newCapacity = (oldCapacity * 3)/2 + 1;
        if (newCapacity < minCapacity)
            newCapacity = minCapacity;
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
}

Vector中容量增长的主要函数如下:

private void ensureCapacityHelper(int minCapacity) {
    int oldCapacity = elementData.length;
    // 当Vector的容量不足以容纳当前的全部元素,增加容量大小。
    // 若 容量增量系数>0(即capacityIncrement>0),则将容量增大当capacityIncrement
    // 否则,将容量增大一倍。
    if (minCapacity > oldCapacity) {
        Object[] oldData = elementData;
        int newCapacity = (capacityIncrement > 0) ?
            (oldCapacity + capacityIncrement) : (oldCapacity * 2);
        if (newCapacity < minCapacity) {
            newCapacity = minCapacity;
        }
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
}
  • 对Enumerition支持

 对Enumeration的支持不同。Vector支持通过Enumeration去遍历,而List不支持

原文:https://www.cnblogs.com/skywang12345/p/3308900.html

猜你喜欢

转载自blog.csdn.net/sinat_38430122/article/details/83549249