Java中Vector,ArrayList和LinkedList的区别

来源:互联网 发布:isight9.0软件下载 编辑:程序博客网 时间:2024/04/30 03:45

三者都是List接口的常见实现,先看官方文档中的描述
Vector:

The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

这里称呼Vector为一种可增长的数组。由于本质是数组,因此可以通过标号来高效地随机访问。且数组大小可以在添加和删除元素时根据需要变化。

Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector’s storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.

上面一段话是关于Vector如何实现数组大小变化的,该类中存在一个变量capacityIncrement,每次增长或缩小都以该值为单位以减少容量变化次数,减少再分配时间。

ArrayList:

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)

这段话表明ArrayList是用一种可变尺寸的数组实现的List接口的实现类。除了它不是线程同步的以外,几乎和Vector相同。

LinkedList:

All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.
Note that this implementation is not synchronized. If multiple threads access a linked list concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.

该类可以是为一个双向链表,对任意标号的操作都会导致链表的遍历。该类也是线程不安全的。

综上,Vector和ArrayList均为数组实现,随机访问快插入删除慢,Vector线程安全而ArrayList线程不安全。LinkedList为链表实现,随机访问慢插入删除快,线程不安全。